Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle status (e.g. 503) in Axios OPTIONS response

edit2: https://stackoverflow.com/a/37784969/107282 suggests that I needn't worry because it doesn't happen when on a real device.


I'm using Axios in a VueJS hybrid (Cordova) app and am calling an API.

Axios is (correctly) doing a 'preflight' OPTIONS request before my GET/POST requests, but if the API returns a 503 at that point, my error handling code doesn't get called.

HTTP.post(url, data, {headers: {Authorization: 'Bearer ' + token.getAccessToken()}})
  .then(response => response)
  .catch(error => {
    // Not reached
  });

How do I catch this error status?


edit: screenshot from chrome dev tools:

503 on OPTIONS request

like image 755
jezmck Avatar asked Oct 19 '17 12:10

jezmck


2 Answers

I was able to reproduce the issue and the simplest fix I could find as below

axios.interceptors.response.use(null, (error) => {
    return Promise.reject(error);
});

As you can see in my tests I was able to get the error for and response for different scenarios

Network error

like image 120
Tarun Lalwani Avatar answered Sep 26 '22 15:09

Tarun Lalwani


Axios' Network Error isn't much descriptive. To rethrow it in a better way, we can do something like this, to at least describe what request got the error, and what happened:

instance.interceptors.response.use(null, error => {
  if (error && error.message === 'Network Error') {
    throw new Error(`Potential network CORS preflight error at ${error.config.url}`);
  }
  throw error;
});
like image 23
falsarella Avatar answered Sep 22 '22 15:09

falsarella