簡體   English   中英

捕獲承諾后傳遞錯誤

[英]Pass error after catch on promises

嗨,我很新,很抱歉,如果我的問題沒有正確表達。

我想在全局函數中定義axios js的承諾。 在這里,我想要全局處理/捕獲401狀態並注銷用戶。 我不想在每個查詢中處理它。

這是我處理請求的源全局函數:

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
      }
    })
}

這是我在控制器上使用的示例函數:

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

我的問題是,當存在異常時,我的控制器中的promise catch不會觸發。 怎么實現這個?

更改requestData函數中的return errorthrow error

根據Axios文檔

您可以在處理請求或響應之前攔截請求或響應。

您將要使用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);
});

throw error替換return error是一半的工作。
當我正確時,promise中的throw error將不會調用下一個promise .catch語句。 這將在.then語句中起作用。

這樣它應該工作:

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
      }
    })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM