Yes you are correct, unhandled promise rejection and uncaughtExceptions are not the same. To handle promise rejection you will need to check for "res" value like so
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();
}
The reason we are checking in the response value is because we are using await. when we use await we will get either the resolved response or the rejected response. it will not throw an exception.
throw Error("This is an exception")
This will be catch when using a wrapper around the code like a try-catch.
Another way of solving this issue is by adding a .catch after the fetch. like so
try {
const res = await axios.get("/login").catch(err => console.error(err));
} catch (error) {
const {status} = error.response;
if (status === 401) doSomething();
}
Now if the fetch failed res will be undefined because we only returned what console.error return which is undefined.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…