Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching errors with axios

Tags:

ajax

axios

I can not catch the error response with axios. How to do that? I use something like:

axios
  .post(...)
  .then(response => {
    console.log('Success: ', response)
  }).catch(error => {
    console.log('Error: ', error)
  })

I see that the result of ajax request has 400 status code and the response body looks like {someField:["This field may not be blank"]} (Django backend). That's ok, I'm ready to process these errors in the catch handler.

But they go to the success handler instead. Why so? I see the following output in the console:

Success: Error: Request failed with status code 400
at createError (createError.js:16)
at settle (settle.js:18)
at XMLHttpRequest.handleLoad (xhr.js:77)

The success handler receives axios error object as the result. Why that may be and what to do next? This error object does not contain any usefull information.

UPD. Actually, the error object does contain the useful information, it contains the response object inside. So we can use:

axios
  .post(...)
  .then(response => {
    if (response && response.response) {
      console.log('This is also an error', response.response.status)
    } else {
      console.log('Success: ', response)
    }
  }).catch(error => {
    console.log('Error: ', error)
  })

But that looks super ugly.

The axios version is [email protected].

That's the big project, but I can not find any axios customizations.

like image 260
Kasheftin Avatar asked Oct 13 '17 00:10

Kasheftin


1 Answers

Use Axios interceptors for the response. Check which status you want to force to fail as error so they go through the catch path whenever you receive said status code.

axios.interceptors.response.use(function (response) {
    if (response.status === 400) {
        return Promise.reject(response);
    }
    return response;
}, function (error) {
    // Do something with response error
    return Promise.reject(error);
});

If you are not receiving the expected status code, you might change the way you check the response in the interceptor. You can check any of the elements that Axios response is structured.

axios.interceptors.response.use(function (response) {
    if (response.statusText !== 'OK') {
        return Promise.reject(response);
    }
    return response;
}, function (error) {
    // Do something with response error
    return Promise.reject(error);
});
like image 57
Dez Avatar answered Sep 24 '22 14:09

Dez