我正在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
都不应该被调用。我该如何实现?
答案 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}`);
}
因此,要运行可选步骤,您需要:
// .... 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}`); }