axios使用拦截器处理错误(js承诺)

Wil*_* M. 6 interceptor promise es6-promise axios

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

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

    if (!error.response) {
      // No network connectivity
    }
  }
)
Run Code Online (Sandbox Code Playgroud)

我的请求看起来像这样

service.post('endpoint').then(response => {
  // Successful request
}).catch(error => {
  // Handle error
})
Run Code Online (Sandbox Code Playgroud)

如果出现任何错误,例如不成功的状态代码(例如 400),我不想处理catch第二个代码示例部分中的错误。但是,如果存在网络问题,我不想处理第一个代码示例中的错误。在这种情况下,不应调用第二个代码示例的 、then或。catch我怎样才能实现这个目标?

Man*_*lon 5

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

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}`);
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

function handleError(error) {
  if (error === 'nevermind') {
    return
  }
  console.log(`handleError: ${error}`);
}
Run Code Online (Sandbox Code Playgroud)

这个逻辑可以被隔离:

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}`); }
Run Code Online (Sandbox Code Playgroud)