我将所有API调用集中在一个唯一的文件API.js中,如下所示:
API.js
Class APIContextProvider extends Component {
async apiCallTest() {
var url = random_url
const options = {
url: url,
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json;',
},
};
return await axios(options)
.then(response => {
if (response.status === 200) {
return response.data
}
}).catch(error => {
console.log(error.response.status)
}
);;
}
然后我从另一个组件调用我的API:
OutsideClass.js
async componentDidMount() {
this.context.apiCallTest().then(data => {
// How can I prevent this then() to run when catch() happens?
});
}
所有操作的顺序是:then((.catch((.then((.
我想要的是防止最后一次。如果捕捉到特定错误(如401(,则不会发生,因为我想要全局错误处理。
到处找都找不到解决方案。。。
谢谢!
如果您想全局捕获异常,那么在之后在引导文件中使用axios拦截器
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
axios.interceptors.response.use(
function (response) {
return response;
},
function (error) {
// handle error
if (error.response.status === 422)
return error;
if (error.response.status === 401)
alert(error.response.status + ': ' + error.response.data.message);
});
您可以在catch中再次抛出错误,它将避免then并转到下一个catch。
await axios(options)
.then(response => {
if (response.status === 200) {
return response.data
}
}).catch(error => {
if (error.response.status === 401) {
throw error;
}
console.log(error.response.status)
}