阿西奥斯.即使api返回404错误,如何在try catch finally中获得错误响应 [英] 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.
in finally
, apiRes
will return null.
即使 api 得到 404 响应,响应中仍然有我想使用的有用信息.
Even when the api get a 404 response, there is still useful information in the response that I would like to use.
当 axios 抛出错误时,如何使用 finally
中的错误响应.
How can I use the error response in finally
when axios throws error.
https://jsfiddle.net/jacobgoh101/fdvnsg6u/1/
推荐答案
根据文档,完整响应可作为错误的 response
属性使用.
According to the documentation, the full response is available as a response
property on the error.
所以我会在 catch
块中使用该信息:
So I'd use that information in the catch
block:
(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
中使用它,只需将它保存到一个你可以在那里使用的变量:
But if you want it in finally
instead, just save it to a variable you can use there:
(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
}
})();
这篇关于阿西奥斯.即使api返回404错误,如何在try catch finally中获得错误响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!