Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 with no 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
343 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...