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.
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;
//...
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With