[英]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.