Reputation: 1268
I am trying to use a proper way to handling my errors in my React app with Axios.
When the connection is dead, I won't get a status code, so I can't check the status code of the response. What is the elegant way to handle errors without a status code?
try {
const res = await axios.get("/login");
} catch (error) {
const {status} = error.response;
if (status === 401) doSomething();
}
I get this error:
[Unhandled promise rejection: TypeError: undefined is not an object
Upvotes: 1
Views: 2078
Reputation: 881
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 caught 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 returned which is undefined.
Upvotes: 2