【发布时间】:2020-06-06 16:33:09
【问题描述】:
我将axios 与trycatch 一起使用,但是当api 返回500 内部服务器错误时,代码执行流到catch 但在async 函数代码之外没有执行,我不知道为什么。
这是我的代码:
export async function authRequest(router, path='/', data={}, method='get') {
const authKey = getAuthKey();
try {
const request = await axios({
method,
url: apiUrl + path,
headers: {
'Authorization': "Bearer " + authKey
},
data
});
return request.data;
} catch (error) {
const isLogged = await axios({
method: 'get',
url: apiUrl + '/isLoggedUser',
headers: {
'Authorization': "Bearer " + authKey
}
});
if (isLogged.data == false) {
router.push({
name: 'login'
})
} else {
console.error('Cannot process this request');
return false;
}
}
}
调用这个函数:
const req = await authRequest(
this.$router,
'/video/play',
);
console.log('cannot reach to this statment after 500 error in axios request')
当Axios 引发 500 内部服务器错误时,最后一个 console.log 语句不会执行/到达或任何代码。
请注意:问题出在 axios 500 内部服务器上,它会在 authRequest 函数之外停止进一步的代码执行。
【问题讨论】:
标签: javascript async-await axios