Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there really no way to get the response body from a failed js fetch request?

The new js fetch API fails the promise if the request fails (400):

fetch(uri).catch(function(err) {
   console.log(err);
});

Is there really no way to get the response body when this happens? e.g. to check an error code.

EDIT: I've created a js fiddle: https://jsfiddle.net/4x4xLwqo/ that calls this mockbin endpoint: http://mockbin.org/bin/d87acbb0-526e-4d66-aea4-b827d9c35031/view

EDIT 2: updated jsfiddle to use a better endpoint: https://jsfiddle.net/4x4xLwqo/2/

like image 945
grahamrhay Avatar asked Oct 16 '15 15:10

grahamrhay


People also ask

How do you deal with failed fetch?

The fetch() function will automatically throw an error for network errors but not for HTTP errors such as 4xx or 5xx responses. For HTTP errors we can check the response. ok property to see if the request failed and reject the promise ourselves by calling return Promise.

How can I get the status code from an HTTP error in fetch?

To get the status code of an HTTP request made with the fetch method, access the status property on the response object. The response. status property contains the HTTP status code of the response, e.g. 200 for a successful response or 500 for a server error.

How do I get fetch from API response?

Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method.


1 Answers

fetch won't go into catch if it encounters a HTTP error. You can handle that with a regular then.

From MDN:

A fetch() promise will reject with a TypeError when a network error is encountered, although this usually means permission issues or similar — a 404 does not constitute a network error, for example. An accurate check for a successful fetch() would include checking that the promise resolved, then checking that the Response.ok property has a value of true.

And an accompanying example, from MDN as well:

fetch('flowers.jpg').then(function(response) {
  if(response.ok) {
    response.blob().then(function(myBlob) {
      var objectURL = URL.createObjectURL(myBlob);
      myImage.src = objectURL;
    });
  } else {
    console.log('Network response was not ok.');
  }
})
.catch(function(error) {
  console.log('There has been a problem with your fetch operation: ' + error.message);
});
like image 100
Bartek Banachewicz Avatar answered Sep 18 '22 06:09

Bartek Banachewicz