How to access Axios error response object in catch clause?

Solution 1:

Since TypeScript 4.4, catch clause variables are now defaulted from any to unknown type unless configured not to. This allows for safer handling as it forces users to check the type of caught value in the catch clause before being used. To get rid of that error, you need to use a type guard to narrow down the possible types of the object to let TypeScript know what type it is dealing with.

You can do something like this:

const isAxiosError = (error: unknown): error is AxiosError => {
  return (error as AxiosError).isAxiosError;
};

try {
  // ...
} catch (err) {
  if (isAxiosError(err) && err.response) {
    if (err.response.status === 404) {
      window.alert('User not found');
    } else if (err.response.status === 401) {
      window.alert('Incorrect password');
    } else {
      console.error(err);
    }
  } else {
    console.error(err);
  }
}

You can check out the guide I made specifically for this scenarios. https://www.linkedin.com/posts/michael-bonon_handling-typed-errors-in-typescript-44-activity-6865161464236400640-MkWB