是的,你是对的。未处理的承诺拒绝和 uncaughtExceptions 是不一样的。要处理承诺拒绝,您需要检查“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返回的内容。