Javascript 阿西奥斯。即使api返回404错误,如何在try catch finally中获得错误响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48298890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Axios. How to get error response even when api return 404 error, in try catch finally
提问by Jacob Goh
for e.g.
例如
(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);
}
})();
in finally, apiReswill return null.
in finally,apiRes将返回空值。
Even when the api get a 404 response, there is still useful information in the response that I would like to use.
即使 api 得到 404 响应,响应中仍然有我想使用的有用信息。
How can I use the error response in finallywhen axios throws error.
finally当 axios 抛出错误时,如何使用错误响应。
回答by T.J. Crowder
According to the documentation, the full response is available as a responseproperty on the error.
根据文档,完整的响应可作为response错误的属性。
So I'd use that information in the catchblock:
所以我会在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);
}
})();
But if you want it in finallyinstead, just save it to a variable you can use there:
但是如果你想要它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
}
})();
回答by Oliver
According to the AXIOS documentation (here: https://github.com/axios/axios) you can pass validateStatus: falsein the config object to any axios request.
根据 AXIOS 文档(此处:https: //github.com/axios/axios),您可以将validateStatus: false配置对象传递给任何 axios 请求。
e.g.
例如
axios.get(url, { validateStatus: false })
axios.post(url, postBody, { validateStatus: false })
You can also pass a function like this: validateStatus: (status) => status === 200According to the docs the default behaviour is function that returns true if (200 <= status < 300).
您还可以传递这样的函数:validateStatus: (status) => status === 200根据文档,默认行为是返回 true if (200 <= status < 300) 的函数。

