Failed HTTP responses can be handled in a fetch() request by knowing that :
- Even if the HTTP response code is invalid (404, 500 etc) — fetch() does not consider this to be an error (Promise returned by fetch is still resolved).
- Only when there is a network failure (DNS error, internet unavailable etc) — fetch() considers this as a failed request and will throw an error (Promise returned by fetch is rejected).
- Response.ok property will be set to true if the response status code is between 200-299. And false otherwise.
- Response.status property will hold the HTTP response code (200, 202, 404, 500 etc).
The above scenarios are explained in an example below. For this example, it is assumed that the server responds with a 200 status code, and sends a JSON response. Any response code not equal to 200 is considered as an error in this case.
// make sure to wrap this code inside an async function
try {
let response = await fetch('/ajax.php', { method: 'POST' });
// check if server responded with http response != 200
if(response.status != 200)
throw new Error('Request Failed');
// HTTP request was successful with 200 response code
// start reading the JSON response now
let json_response = await response.json();
// success
}
catch(e) {
// catch error
alert(e.message);
}
The above code may throw error in three cases :
- Promise returned by fetch() may be rejected due to a network error.
- Server responded with a status code not equal to 200, and Javascript code throws an Error object.
- Promise returned by response.json() may be rejected due to invalid JSON response.