我有這段代碼(函式的一部分),注意URL 末尾的“ BadURL ”:
從“axios”匯入 axios;
try {
return axios.post("http://localhost:5000/api/featureFlagBadURL", {
flagName: "newJqueryAjaxListener",
defaultValue: "false",
});
} catch (error) {
return { data: 'false' }
}
但是進不去catch塊,說:
(node:7676) UnhandledPromiseRejectionWarning: Error: Request failed with status code 404
僅當我將函式呼叫本身包裝在類之外時,我才能捕獲錯誤
uj5u.com熱心網友回復:
Axios.post(...) 是一個回傳承諾的異步呼叫,該陳述句不會失敗,即使失敗,也不是因為 HTTP 請求失敗。
您需要使用的是回傳的承諾的.then()和.catch()方法來處理請求。
return axios.post("http://localhost:5000/api/featureFlagBadURL", {
flagName: "newJqueryAjaxListener",
defaultValue: "false"
}).then((results) => {
console.log('yay', results);
}).catch((error) => {
console.log('oops', error);
});
另一種選擇是使用async await.
async function handler() {
try {
const results = await axios.post("http://localhost:5000/api/featureFlagBadURL", {
flagName: "newJqueryAjaxListener",
defaultValue: "false",
});
console.log('yay', results);
}
catch (error) {
console.log('oops', error);
return { data: 'false' };
}
})
uj5u.com熱心網友回復:
試試這個方法:
return axios.post("http://localhost:5000/api/featureFlagBadURL", {
flagName: "newJqueryAjaxListener",
defaultValue: "false",
}).then(function (response) {
// handle success
console.log(response);
}).catch(function (error) {
// handle error
console.log(error);
}).then(function () {
// always executed
});
來源
uj5u.com熱心網友回復:
您可以捕獲錯誤并檢查狀態代碼。那么你可以處理它。也許巫婆開關案例或簡單的如果。我是為 404 做的。見下面的鱈魚:
axios.post("http://localhost:5000/api/featureFlagBadURL", {
flagName: "newJqueryAjaxListener",
defaultValue: "false",
}).then((res) => {
// handle response => res.data
console.log(response);
}).catch((error) => {
if (error.response) {
if(error.response.status === 404) {
console.log('BAD URL')
// or
console.log(error)
}
}
}
uj5u.com熱心網友回復:
如果函式有大量資料,請嘗試通過將代碼包含在函式中來使用異步等待。
或者嘗試將埠從 5000 更改為 4000 或 3000。看看這是否有效!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/339822.html
標籤:javascript 公理
上一篇:十進制的正則運算式模式匹配
