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

6

我正在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部分处理该错误。但是,如果存在网络问题,我希望在第一个代码示例中处理该错误。在这种情况下,既不应调用第二个代码示例中的then,也不应调用catch。我该如何实现这一点?


1
你确定 if (!error.response) 是检测无网络活动的好方法吗?我无法验证。 - Roamer-1888
1个回答

4

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接