axios: Add AxiosException class

Is your feature request related to a problem? Please describe. I use typescript. How to verify that I received exactly axios error?

Describe the solution you’d like Add custom error class: AxiosException, which is inherited from the standard Error class

Example

try {
  axios.get('...')
}
catch(err) {
  if (err instanceof AxiosException) {
      console.error(err.response);
  }
}

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 15
  • Comments: 20 (2 by maintainers)

Most upvoted comments

You can apply type guards with the isAxiosError helper function.

https://github.com/axios/axios/blob/f3ca6371caa738ba5308d413433d9f676f2e0138/index.d.ts#L168

https://github.com/axios/axios/blob/f3ca6371caa738ba5308d413433d9f676f2e0138/test/typescript/axios.ts#L369-L372

import axios from 'axios';

if (axios.isAxiosError(error)) {
  // error.response?.data ...
}

@ruscon I think you can use type assertion.

import axios, {AxiosError} from 'axios';

try {
  axios.get('...')
}
catch(err) {
  if ((<any>err).isAxiosError) { // check to make sure type assertion is right
      const e = <AxiosError>error;
      console.error(e.response);
  }
}

Having a specific exception would be nice but AxiosError is definitely not useless. You can write a helper around it, something like:

export function isAxiosError<T>(error: AxiosError | any): error is AxiosError<T> {
  return error && error.isAxiosError
}

And then use it like this:

  catch (exception) {
    if (isAxiosError<apiTypes.ResponseError>(exception) && exception.response) {
       ...
    }
  }

OMG. 1 year of jerking with it.

@jasonsaayman did it land in any currently released version?

@chinesedfan So you can do something like this:

import axios, {AxiosError} from 'axios';

try {
    axios.get('...')
}
catch(err) {
    if (err.isAxiosError) { // no types
        const e: AxiosError = error;
        console.error(e.response);
    }
}

But this is a bad approach for both js and ts.

What’s the state of having AxiosError be a class as well as an interface in order to be able to use instanceof ?

@chinesedfan Typescript needs typing. The typification of the class Error does not know anything about this property. and the interface in this case also does not work normally. Those, the only option is a class

@darkbasic I don’t think so. I have to add the sha to my package.json:

"axios": "https://github.com/axios/axios.git#58112e137e316c7154e77a3b3777d6788de869b9",

I ran into this issue because Typescript 4.4 defaults catch {} error type to unknown instead of any now, and checking error instanceof AxiosException is the cleanest way to fix it.