简体   繁体   中英

Handling status code error - try catch Axios on dead connection

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM