npmpromise95% confidence\u2191 351

Axios handling errors

Full error message
I'm trying to understand javascript promises better with Axios. What I pretend is to handle all errors in Request.js and only call the request function from anywhere without having to use catch().

In this example, the response to the request will be 400 with an error message in JSON.

This is the error I'm getting:

Uncaught (in promise) Error: Request failed with status code 400

The only solution I find is to add .catch(() => {}) in Somewhere.js but I'm trying to avoid having to do that. Is it possible?

Here's the code:

  Request.js

export function request(method, uri, body, headers) {
  let config = {
    method: method.toLowerCase(),
    url: uri,
    baseURL: API_URL,
    headers: { 'Authorization': 'Bearer ' + getToken() },
    validateStatus: function (status) {
      return status >= 200 && status < 400
    }
  }

  ...

  return axios(config).then(
    function (response) {
      return response.data
    }
  ).catch(
    function (error) {
      console.log('Show error notification!')
      return Promise.reject(error)
    }
  )
}

  Somewhere.js

export default class Somewhere extends React.Component {

  ...

  callSomeRequest() {
    request('DELETE', '/some/request').then(
      () => {
        console.log('Request successful!')
      }
    )
  }

  ...

}

If you want to handle all basic errors in your request module, without needing to use catch on each call, then the Axios approach is to use an interceptor on the responses: axios.interceptors.response.use(function (response) { // Optional: Do something with response data return response; }, function (error) { // Do whatever you want with the response error here: // But, be SURE to return the rejected promise, so the caller still has // the option of additional specialized handling at the call-site: return Promise.reject(error); }); If you return the error from your axios interceptor, then you can still also use the conventional approach via a catch() block, like below: axios.get('/api/xyz/abcd') .catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser // and an instance of http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } });

API access

Get this solution programmatically \u2014 free, no authentication.

curl https://depscope.dev/api/error/11215cad4e6713a56d3b31a712301b74cc41215c8c9effce2389abce03498b67
hash \u00b7 11215cad4e6713a56d3b31a712301b74cc41215c8c9effce2389abce03498b67
Axios handling errors — DepScope fix | DepScope