Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you type an error property in a catch block in TypeScript?

I have this code:

import axios, {AxiosError} from "axios";

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

I can't check the status code inside because of TypeScript. How do I 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.

like image 730
Ksenia Avatar asked Sep 01 '25 10:09

Ksenia


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;
   //...
}
like image 181
Nicholas Tower Avatar answered Sep 03 '25 01:09

Nicholas Tower


The best way to do this, is to explicitly check for the Error you expect to get. In this case, if you want to check if it's an AxiosError do the following:

import axios, {AxiosError} from "axios";

try {
  some request
} catch(err) {
 if (err instanceof AxiosError) {
   console.log(error.response);
   if(error.response?.data?.statusCode === 401) {
     logout();
   } 
 } else {
   // it was some other kind of error, handle it appropriately
 } 

By checking if it's an instance of AxiosError, in the if block we narrow the type of the err variable to be AxiosError. In the examples where people are using as to cast the Error, that could be incorrect because the error might NOT be an AxiosError but some other kind of error, which would result in a runtime error.

like image 22
Bart Dorsey Avatar answered Sep 03 '25 03:09

Bart Dorsey