[英]Handling status code error - try catch Axios on dead connection
我正在尝试使用正确的方法在我的 React 应用程序中使用 Axios 处理我的错误。
当连接死了,我不会得到状态码,所以我无法检查响应的状态码。 在没有状态码的情况下处理错误的优雅方法是什么?
try {
const res = await axios.get("/login");
} catch (error) {
const {status} = error.response;
if (status === 401) doSomething();
}
我收到此错误:
[未处理的 promise 拒绝:TypeError: undefined is not an object
是的,你是对的。 未处理的 promise 拒绝和 uncaughtExceptions 是不一样的。 要处理 promise 拒绝,您需要检查“res”值,如下所示:
try {
const res = await axios.get("/login");
if(res.err) {
// An error exist
// Do handle response error
}
} catch (error) {
const {status} = error.response;
if (status === 401) doSomething();
}
我们检查响应值的原因是因为我们正在使用等待。 当我们使用 await 时,我们将得到已解决的响应或被拒绝的响应。 它不会抛出异常。
throw Error("This is an exception")
当使用try-catch之类的代码包装器时,这将被捕获。
解决此问题的另一种方法是在 fetch 之后添加.catch 。 像这样:
try {
const res = await axios.get("/login").catch(err => console.error(err));
} catch (error) {
const {status} = error.response;
if (status === 401) doSomething();
}
现在如果获取失败, res
将是未定义的,因为我们只返回了未定义的console.error返回的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.