简体   繁体   中英

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).

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:

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 ?

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. Feel free to update it.

https://jsfiddle.net/180ruamk/

It'll be exactly the same code as in your then callback:

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
}

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