[英]Axios. How to get error response even when api return 404 error, in try catch finally
例如
(async() => {
let apiRes = null;
try {
apiRes = await axios.get('https://silex.edgeprop.my/api/v1/a');
} catch (err) {
console.error(err);
} finally {
console.log(apiRes);
}
})();
在finally
中, apiRes
將返回 null。
即使 api 得到 404 響應,響應中仍然有我想使用的有用信息。
當 axios 拋出錯誤時,如何在finally
中使用錯誤響應。
根據文檔 ,完整響應可用作錯誤的response
屬性。
所以我會在catch
塊中使用這些信息:
(async() => {
let apiRes = null;
try {
apiRes = await axios.get('https://silex.edgeprop.my/api/v1/a');
} catch (err) {
console.error("Error response:");
console.error(err.response.data); // ***
console.error(err.response.status); // ***
console.error(err.response.headers); // ***
} finally {
console.log(apiRes);
}
})();
但是如果你finally
想要它,只需將它保存到你可以在那里使用的變量:
(async() => {
let apiRes = null;
try {
apiRes = await axios.get('https://silex.edgeprop.my/api/v1/a');
} catch (err) {
apiRes = err.response;
} finally {
console.log(apiRes); // Could be success or error
}
})();
根據AXIOS文檔(此處: https : //github.com/axios/axios ),您可以將config對象中的validateStatus: false
傳遞給任何axios請求。
例如
axios.get(url, { validateStatus: false })
axios.post(url, postBody, { validateStatus: false })
您還可以傳遞這樣的函數: validateStatus: (status) => status === 200
根據文檔,默認行為是函數,如果(200 <= status <300)則返回true。
您可以處理狀態碼:
使用 Ts 的示例:
let conf: AxiosRequestConfig = {};
conf.validateStatus = (status: number) => {
return (status >= 200 && status < 300) || status == 404
}
let response = await req.get(url, conf);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.