Let's imagine we are calling an API with axios
within a try...catch
block to get a list of posts. If the request is successful then we will get the response data, else we will get the error on our catch
block
const fetchPosts = async () => {
try {
const response = await axios.get(
"<https://jsonplaceholder.typicode.com/posts>"
);
// Do something with the response
} catch (error) {
// Need to handle this error
}
};
But the problem is typescript assumes this error
object as unknown
type. So, typescript won't allow us to access any properties inside this error
object.
To handle this situation, we can assert the error
object type like this
import axios, {AxiosError} from "axios";
const fetchPosts = async () => {
try {
const response = await axios.get(
"<https://jsonplaceholder.typicode.com/posts>"
);
// Do something with the response
} catch (e) {
const error = e as AxiosError;
// Need to handle this error
}
};
But the assertion is not a good practice and we should avoid doing this. By asserting type you are forcing the typescript to stop doing his work. So this may be problematic sometimes.
A Good Solution
We can use typeguard to handle this kind of situation and axios
also provides a typeguard
for handling errors. Here how it looks like
const fetchPosts = async () => {
try {
const response = await axios.get(
"<https://jsonplaceholder.typicode.com/posts>"
);
// Do something with the response
} catch (error) {
if (axios.isAxiosError(error)) {
console.log(error.status)
console.error(error.response);
// Do something with this error...
} else {
console.error(error);
}
}
};
We can also pass generic to type the error response
and request
object with this typeguard
.
interface ValidationError {
message: string;
errors: Record<string, string[]>
}
const fetchPosts = async () => {
try {
const response = await axios.get(
"<https://jsonplaceholder.typicode.com/posts>"
);
// Do something with the response
} catch (error) {
if (axios.isAxiosError<ValidationError, Record<string, unknown>>(error)) {
console.log(error.status)
console.error(error.response);
// Do something with this error...
} else {
console.error(error);
}
}
};
N:B: You can also use this in a .catch()
method.
To learn about more tips and tricks with typescript, follow me on LinkedIn
Top comments (5)
Thanks!
Thanks for sharing.
saved my life, thank you
Thanks , I was looking for these since from an hour
Thanks... I was searching for this one :)