简体   繁体   中英

Pass error after catch on promises

Hi I'm new so sorry if my question does not formulate properly.

I want to define a promise from axios js in a global function. Here I want to handle / catch the 401 status globally and logout the user. I do not want to handle it in every single query.

Here my source global function to handle a request:

export function requestData (url, payload = {}) {
  return axios.post(url, payload)
    .then(response => {
      return response.data
    })
    .catch(error => {
      if (error.response.status === 401) {
        logout()
      } else {
        return error
      }
    })
}

And here a example function I use on a controller:

requestData('/api/persons', {options: this.options, search: search})
  .then(data => {
    this.data = data
  })
  .catch(error => {
    this.error = error.toString()
  })

My Problem is that the promise catch in my controller will not fire when there is an exception. How to realize this?

更改requestData函数中的return errorthrow error

As per the Axios docs

You can intercept requests or responses before they are handled by then or catch.

You're going to want to use the Response Interceptor:

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

Replacing return error by throw error is the half work.
When I'm right the throw error in promise catch will not invoke the next promise .catch statement. This will work in the .then statement.

This way it should work:

export function requestData (url, payload = {}) {
  return axios.post(url, payload)
    .then(response => {
      return response.data
    })
    .catch(error => {
      if (error.response.status === 401) {
        logout()
      } else {
        return error
      }
    })
   .then(result => {
      if (result instanceof Error) {
        throw result
      } else {
        return result
      }
    })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM