[英]Handling status code error - try catch Axios on dead connection
我正在嘗試使用正確的方法在我的 React 應用程序中使用 Axios 處理我的錯誤。
當連接死了,我不會得到狀態碼,所以我無法檢查響應的狀態碼。 在沒有狀態碼的情況下處理錯誤的優雅方法是什么?
try {
const res = await axios.get("/login");
} catch (error) {
const {status} = error.response;
if (status === 401) doSomething();
}
我收到此錯誤:
[未處理的 promise 拒絕:TypeError: undefined is not an object
是的,你是對的。 未處理的 promise 拒絕和 uncaughtExceptions 是不一樣的。 要處理 promise 拒絕,您需要檢查“res”值,如下所示:
try {
const res = await axios.get("/login");
if(res.err) {
// An error exist
// Do handle response error
}
} catch (error) {
const {status} = error.response;
if (status === 401) doSomething();
}
我們檢查響應值的原因是因為我們正在使用等待。 當我們使用 await 時,我們將得到已解決的響應或被拒絕的響應。 它不會拋出異常。
throw Error("This is an exception")
當使用try-catch之類的代碼包裝器時,這將被捕獲。
解決此問題的另一種方法是在 fetch 之后添加.catch 。 像這樣:
try {
const res = await axios.get("/login").catch(err => console.error(err));
} catch (error) {
const {status} = error.response;
if (status === 401) doSomething();
}
現在如果獲取失敗, res
將是未定義的,因為我們只返回了未定義的console.error返回的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.