例如
(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
中使用错误响应。
最佳答案
根据 the documentation ,完整的响应作为错误的 response
属性提供。
所以我会在 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
中使用它,只需将它保存到一个你可以在那里使用的变量中:
(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
}
})();
关于javascript - 公理。即使 api 返回 404 错误,如何在 try catch finally 中获得错误响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48298890/