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/
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.
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.
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.
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 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 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);
});
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