【问题标题】:How to catch the status code when fetch fails using async await使用异步等待获取失败时如何捕获状态代码
【发布时间】:2019-07-10 16:18:03
【问题描述】:

上下文

对于我的fetch 请求之一(我在Vuex action 中使用,但这不是理解我的问题所必需的),我将从使用Promisesasync/await

使用下面的代码,如果请求失败,我可以根据我的响应状态代码向最终用户提供错误消息。

fetch("http://localhost:8000/api/v1/book", {
  headers: {
    Accept: "application/json"
  }
}).then(response => {
  if (!response.ok) {
    if (response.status === 429) {
      // displaying "wow, slow down mate"
    } else if (response.status === 403) {
      // displaying "hm, what about no?"
    } else {
      // displaying "dunno what happened \_(ツ)_/¯"   
    }

    throw new Error(response);
  } else {
    return response.json();
  }
}).then(books => {
  // storing my books in my Vuex store
})
.catch(error => {
  // storing my error onto Sentry
});

问题

使用async/await,这就是我的代码现在的样子:

try {
  const response = await fetch("http://localhost:8000/api/v1/book", {
    headers: {
      Accept: "application/json"
    }
  });

  const books = await response.json();

  // storing my books
} catch(exception) {
  // storing my error onto Sentry
}

问题

如果使用async/await 失败,我如何确定我的响应返回了哪个状态代码?

如果我以错误的方式使用它,请不要犹豫,用更好的模式纠正我。

备注

我制作了一个 JSFiddle 来现场测试这个问题。随时更新。

https://jsfiddle.net/180ruamk/

【问题讨论】:

  • 不使用async / await..response.status等时完全一样
  • 但是要和你的thenable 一样,你的const books 想要在你的捕获中..
  • 我试过了,但我无法在await fetch() 之后访问我的response.status,因为它直接进入了catch(exception) 块,并且异常错过了响应数据。

标签: javascript error-handling async-await


【解决方案1】:

它将与您的 then 回调中的代码完全相同:

try {
  const response = await fetch("http://localhost:8000/api/v1/book", {
    headers: {
      Accept: "application/json"
    }
  });
  if (!response.ok) {
    if (response.status === 429) {
      // displaying "wow, slow down mate"
    } else if (response.status === 403) {
      // displaying "hm, what about no?"
    } else {
      // displaying "dunno what happened \_(ツ)_/¯"   
    }
    throw new Error(response);
  }
  const books = await response.json();

  // storing my books
} catch(exception) {
  // storing my error onto Sentry
}

【讨论】:

    猜你喜欢
    • 2020-09-21
    • 2019-10-10
    • 2014-12-01
    • 1970-01-01
    • 2021-11-26
    • 2022-07-06
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多