We have the following call to fetch
.
this.http.fetch('flasher', { method: 'post', body: jsonPayload }) .then(response => response.json()) .then(data => console.log(data));
This works when we receive a 200 response but logs nothing to the console when we receive a 500 response. How do we handle a 500?
The Fetch API allows you to asynchronously request for a resource. Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.
The Promise returned from fetch() won't reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
Combining then
with catch
works.
fetch('http://some-site.com/api/some.json') .then(function(response) { // first then() if(response.ok) { return response.text(); } throw new Error('Something went wrong.'); }) .then(function(text) { // second then() console.log('Request successful', text); }) .catch(function(error) { // catch console.log('Request failed', error); });
fetch()
returns a Promise
containing a Response
object. The Promise
can become either fulfilled or rejected. Fulfillment runs the first then()
, returns its promise, and runs the second then()
. Rejection throws on the first then()
and jumps to the catch()
.
MDN - Promise
MDN - Checking that the fetch was successful
Google - Introduction to Fetch
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With