Jac*_*Goh 9 javascript error-handling axios
例如
(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);
}
})();
Run Code Online (Sandbox Code Playgroud)
中的finally,apiRes将返回null。
即使api收到404响应,响应中仍然有一些我想使用的有用信息。
finally当axios引发错误时,如何使用错误响应。
T.J*_*der 18
根据文档,完整的响应可用作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);
}
})();
Run Code Online (Sandbox Code Playgroud)
但是,如果您希望将其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
}
})();
Run Code Online (Sandbox Code Playgroud)
根据AXIOS文档(这里:https : //github.com/axios/axios),您可以将validateStatus: falseconfig对象传递给任何axios请求。
例如
axios.get(url, { validateStatus: false })
axios.post(url, postBody, { validateStatus: false })
Run Code Online (Sandbox Code Playgroud)
您还可以传递如下函数:validateStatus: (status) => status === 200
根据文档,默认行为是如果(200 <= status <300)返回true的函数。
小智 5
您可以处理状态码:
使用 T 的示例:
let conf: AxiosRequestConfig = {};
conf.validateStatus = (status: number) => {
return (status >= 200 && status < 300) || status == 404
}
let response = await req.get(url, conf);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15099 次 |
| 最近记录: |