DEV Community

Md Mostafizur Rahman
Md Mostafizur Rahman

Posted on

Handle Axios Error in Typescript

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

Enter fullscreen mode Exit fullscreen mode

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
  }
};
Enter fullscreen mode Exit fullscreen mode

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);
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

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);
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
rafaelsilveeira profile image
Rafael S. da Rosa

Thanks!

Collapse
 
abi0l9 profile image
Monsur Oyedeji

Thanks for sharing.

Collapse
 
fisayodoris profile image
fisayo~

saved my life, thank you

Collapse
 
kapilbamotriya123 profile image
kapilbamotriya123

Thanks , I was looking for these since from an hour

Collapse
 
hihabib profile image
Habibul Islam • Edited

Thanks... I was searching for this one :)