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

Viewed 20880

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?

3 Answers

Use AxiosError to cast error

import  { AxiosError } from 'axios';

catch (error) {
  const err = error as AxiosError
  console.log(err.response?.data)
}

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

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");
      } 
   } 
}

Related