Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

283
Views
axios Error typescript, annotation must be 'any' or 'unknown' if?

I got error of Catch clause variable type annotation must be 'any' or 'unknown' if specified.ts(1196)

with below code

import axios, { AxiosError } from "axios";
try {
        
    } catch(error: AxiosError) {
      throw Error(error);
    }

How to throw axios error in TS?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Use AxiosError to cast error

import  { AxiosError } from 'axios';

catch (error) {
  const err = error as AxiosError
  console.log(err.response?.data)
}
about 4 years ago · Juan Pablo Isaza Report

0

I would suggest to you, removing the error type like the following:

import axios from 'axios';

try {
  // do what you want with axios
  // axios.get('https://example.com/some-api');
} catch (error) {
  // check if the error was thrown from axios
  if (axios.isAxiosError(error)) {
    // do something
    // or just re-throw the error
    throw error;
  } else {
    // do something else
    // or creating a new error
    throw new Error('different error than axios');
  }
}

I just created a stackblitz for it. And if you want to have a deeper look just have a look at this article

about 4 years ago · Juan Pablo Isaza Report

0

You cannot write a specific annotation for the catch clause variable in typescript, this is because in javascript a catch clause will catch any exception that is thrown, not just exceptions of a specified type.

In typescript, if you want to catch just a specific type of exception, you have to catch whatever is thrown, check if it is the type of exception you want to handle, and if not, throw it again.

meaning: check if the error that is thrown is an axios error first, before doing anything.

try {
// do something
}catch (err) {
     // check if error is an axios error
     if (axios.isAxiosError(err)) {
                
      // console.log(err.response?.data)
      if (!err?.response) {
          console.log("No Server Response");
       } else if (err.response?.status === 400) {
         console.log("Missing Username or Password");
       } else if (err.response?.status === 401) {
         console.log("Unauthorized");
        } else {
        console.log("Login Failed");
      } 
   } 
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!