简体   繁体   English

使用异步等待获取失败时如何捕获状态代码

[英]How to catch the status code when fetch fails using async await

Context 语境

I am going from using Promises to async/await for one of my fetch request (which I use inside a Vuex action , but this is not necessary to understand my issue). 我将从使用Promises 异步/等待 获取请求之一(我在Vuex action中使用了该请求,但这对于理解我的问题不是必需的)。

Using the code below, I am able to provide the end user an error message depending the status code of my response in case the request failed. 使用以下代码,如果请求失败,我可以根据响应的状态代码向最终用户提供错误消息。

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
});

Issue 问题

Using async/await , this is what my code looks like now: 使用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
}

Question

How can I figure out which status code my response returned in case it failed using async/await ? 如果使用async/await失败,如何确定响应返回的状态码?

If I am using this in the wrong way, just do not hesitate to correct me with a better pattern. 如果我以错误的方式使用它,请不要犹豫,以更好的方式纠正我。

Notes 笔记

I have made a JSFiddle to test the issue live. 我做了一个JSFiddle来实时测试该问题。 Feel free to update it. 随时更新。

https://jsfiddle.net/180ruamk/ https://jsfiddle.net/180ruamk/

It'll be exactly the same code as in your then callback: 这将与您的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
}

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

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