Axios使用拦截器处理错误(JS Promise)

时间:2020-08-08 16:58:53

标签: promise axios es6-promise interceptor

我正在axios中使用拦截器来检查错误。

service.interceptors.response.use(
  response => response,
  error => {
    const originalRequest = error.config

    if (!error.response) {
      // No network connectivity
    }
  }
)

我的请求看起来像这样

service.post('endpoint').then(response => {
  // Successful request
}).catch(error => {
  // Handle error
})

如果有任何错误,例如不成功的状态代码(例如400),我将不处理第二个代码示例的catch部分中的错误。但是,如果出现网络问题,我将不处理第一个代码示例中的错误。在那种情况下,第二个代码示例的thencatch都不应该被调用。我该如何实现?

1 个答案:

答案 0 :(得分:0)

当您已经有了一个承诺链时,您将无法停止流程:

const axios = require('axios')

axios.interceptors.response.use(
  response => response,
  manageErrorConnection
)

// here you have created a promise chain that can't be changed:
axios.get('http://localhost:3000/user?ID=12345')
  .then(handleResponse)
  .catch(handleError)

function manageErrorConnection(err) {
  if (err.response && err.response.status >= 400 && err.response.status <= 500) {
    // this will trigger the `handleError` function in the promise chain
    return Promise.reject(new Error('Bad status code'))
  } else if (err.code === 'ECONNREFUSED') {
    // this will trigger the `handlerResponse` function in the promise chain
    // bacause we are not returning a rejection! Just an example
    return 'nevermind'
  } else {
    // this will trigger the `handleError` function in the promise chain
    return Promise.reject(err)
  }
}

function handleResponse(response) {
  console.log(`handleResponse: ${response}`);
}

function handleError(error) {
  console.log(`handleError: ${error}`);
}

因此,要运行可选步骤,您需要:

  1. 将逻辑放入处理程序中,以跳过它
  2. 在需要时将处理程序放入链中(我会避免这样做,因为它是“意大利面条软件”)

  1. 将逻辑放在处理程序示例中
// .... changing this line ...
    return Promise.reject('nevermind')
// ....

function handleError(error) {
  if (error === 'nevermind') {
    return
  }
  console.log(`handleError: ${error}`);
}

这种逻辑可以被隔离:

axios.get('http://google.it/user?ID=12345')
  .then(handleResponse)
  .catch(shouldHandleError)
  .catch(handleError)

function manageErrorConnection(err) { return Promise.reject('nevermind') }

function handleResponse(response) { console.log(`handleResponse: ${response}`); }

function shouldHandleError(error) {
  if (error === 'nevermind') {
    // this stop the chain
    console.log('avoid handling');
    return
  }
  return Promise.reject(error)
}

function handleError(error) { console.log(`handleError: ${error}`); }