Ben
Ben

Reputation: 16649

Accessing Axios error codes in interceptor

When using axios response interceptors in client-side JavaScript/React/etc, how can I access error codes such as the following:

I noticed that these codes get printed to the console by axios/lib/adapters/xhr.js, but I can't seem to work out how to access them myself in my response interceptor?

Code:

axios.interceptors.response.use(null, (error) => {

    console.log(error.???);

    return Promise.reject(error);
}

NB: The point is to be able to distinguish between "Your internet is down" and "Our API is down" when showing an error message to the user.

Upvotes: 0

Views: 1277

Answers (2)

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22885

You can get status like this error.response.status but write safe code since it is not always true. In case of 502, error.response is undefined and will break

Here is how you can handle your errors

axios.interceptors.response.use(null, (error) => {
  if (error.message === 'Network Error') {
    if (error?.response?.status) === 504) {
      throw {
        message: 'Something went wrong. Please try again later.',
      };
    } else {
      throw {
        message: 'You are not connected to the internet. Verify your connection and then try again.',
      };
    }
  }
  if (error.response) {
    if (error.response.status === 500) {
      throw {
        message: 'Something went wrong. Please try again later.',
      };
    }
    if (error.response.status === 401) {
      // logout logic
    }
    if (error.response.status === 403) {
      // redirect user to some home page since that action is not allowed
    }
    throw { ...error.response.data, statusCode: error.response.status };
  }
  throw {
    message: 'Something went wrong. Please try again later.',
  };
});

Upvotes: 1

hane Smitter
hane Smitter

Reputation: 870

You can access Axios error codes via error.code from your interceptors. For example:

axios.interceptors.response.use(null, (error) => {

    console.log(error.code);

    return Promise.reject(error);
}

The possible error codes defined by axios can be found in their docs.

You mentioned:

NB: The point is to be able to distinguish between "Your internet is down" and "Our API is down" when showing an error message to the user.

This may be impossible to achieve since axios is not be able to distinguish when "your internet is down"(no internet connection) or "API is down"(Bad DNS). Axios will report a generalized "Network_Error".

This is not an issue with axios, but the underlying XMLHttpRequest. For security reasons details about the network error is not exposed to JS. You can find out for yourself with the barebones XMLHttpRequest like so:

let xhr = new XMLHttpRequest()
xhr.onerror = (e) => console.log("There is not much network info here", e, xhr)
xhr.open("GET", "https://zacky.web.app")
xhr.send()

Upvotes: 0

Related Questions