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 badges1 Answer
Reset to default 10fetch
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 aTypeError
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 successfulfetch()
would include checking that the promise resolved, then checking that theResponse.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);
});
版权声明:本文标题:javascript - Is there really no way to get the response body from a failed js fetch request? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741335543a2373018.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论