admin管理员组

文章数量:1288077

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: / that calls this mockbin endpoint:

EDIT 2: updated jsfiddle to use a better endpoint: /

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/4x4xLwqo/ that calls this mockbin endpoint: http://mockbin/bin/d87acbb0-526e-4d66-aea4-b827d9c35031/view

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

Share Improve this question edited Oct 18, 2015 at 18:25 grahamrhay asked Oct 16, 2015 at 15:31 grahamrhaygrahamrhay 2,1664 gold badges22 silver badges30 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

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

本文标签: javascriptIs there really no way to get the response body from a failed js fetch requestStack Overflow