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
, apiRes
将返回 null。
即使 api 收到 404 响应,响应中仍然有我想使用的有用信息。
我如何使用错误响应finally
当 axios 抛出错误时。
https://jsfiddle.net/jacobgoh101/fdvnsg6u/1/ https://jsfiddle.net/jacobgoh101/fdvnsg6u/1/
根据文档 https://github.com/axios/axios#handling-errors,完整的响应可作为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);
}
})();
更新了小提琴 https://jsfiddle.net/fdvnsg6u/2/
但如果你想要它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
}
})();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)