简体   繁体   English

处理状态码错误 - 尝试在死连接上捕获 Axios

[英]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.我正在尝试使用正确的方法在我的 React 应用程序中使用 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 [未处理的 promise 拒绝:TypeError: undefined is not an object

Yes, you are correct.是的,你是对的。 Unhandled promise rejection and uncaughtExceptions are not the same.未处理的 promise 拒绝和 uncaughtExceptions 是不一样的。 To handle promise rejection you will need to check for "res" value like so:要处理 promise 拒绝,您需要检查“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();
}

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.当我们使用 await 时,我们将得到已解决的响应或被拒绝的响应。 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 .当使用try-catch之类的代码包装器时,这将被捕获。

Another way of solving this issue is by adding a .catch after the fetch.解决此问题的另一种方法是在 fetch 之后添加.catch 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.现在如果获取失败, res将是未定义的,因为我们只返回了未定义的console.error返回的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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