How type error property in catch block typescript?

Viewed 941

I have next code:

import axios, {AxiosError} from "axios";

try {
  some request
} catch(err:AxiosError) {
 console.log(error.response) //doesnt work
 console.log(error.response?.data?.message) //doesnt work
 if(error.response?.data?.statusCode === 401) {
   logout()
 }
}

I cannot check status code inside bacause of typescript how to describe the error type correctly without resorting to the any type? I couldn't find how people handle this error in typescript, maybe I'm missing something

2 Answers

Typescript has no way to verify which types of values might be thrown by arbitrary code. So up until recently, the error had to be of type any.

} catch (err: any) {

From version 4.0 onward, typescript also allows unknown.

} catch (err: unknown) {

Anything else is not supported. If you want something more specific, you will either need to write code to narrow down what type of thing was thrown, or you will need to use a type assertion. Keep in mind that a type assertion is a way to tell typescript "i know more than you do, so don't check my work". If you assert that it's an AxiosError, but it could actually be something else, typescript cannot point out that mistake to you.

catch (err: unknown) {
   const error = err as AxiosError;
   //...
}

Alternatively, rather than use a regular catch block, restructure the code to use the Promise.catch(error) method. You can then quote the type of the parameter as (error: AxiosError) or just leave TypeScript to infer the type.

e.g., assuming "some request" is a GET request, it might look like this:

import axios from 'axios';

await (async () => {
  axios
    .get('some-url')
    .then((response) => {
      // Some handler logic
    })
    .catch((error) => {
      console.log(error.response); // now works
      console.log(error.response?.data?.message); // now works
      if (error.response?.data?.statusCode === 401) {
        logout()
      }
    });
})();
Related