[英]Code Execution stops after axios 500 internal server error
我使用的是axios
与trycatch
但是当API返回500内部服务器错误,代码执行流向捕获但外界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')
由于最后一个console.log
语句在Axios
抛出 500 内部服务器错误后不会执行/到达或任何代码。
请注意:问题出在 axios 500 内部服务器上,它会在authRequest
函数之外停止进一步的代码执行。
您在 catch 块中发出的 Axios 请求应该被 try/catch 包围。 除了2XX
之外的任何响应都将进入 catch 块(抛出错误)。
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) {
try {
const isLogged = await axios({
method: 'get',
url: apiUrl + '/isLoggedUser',
headers: {
'Authorization': "Bearer " + authKey
}
});
if (isLogged.data == false) {
router.push({
name: 'login'
})
}
} catch (e) {
console.error('Cannot process this request');
return false;
}
}
}
您可以在调用authRequest
时尝试使用 try/catch authRequest
?
try{
const req = await authRequest(
this.$router,
'/video/play',
);
console.log('cannot reach to this statment after 500 error in axios request')
}
catch(e){
console.log('cannot reach to this statment after 500 error in axios request')
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.