JavaScript
HTTP error handling
Learn to catch HTTP errors with response.ok and status.
fetch does not catch HTTP errors
fetch behaves unexpectedly: it does not reject the promise unless there is a network error. Even if the server returns 404 or 500, the promise resolves and gives you a Response object.
const response = await fetch(url);
if (!response.ok) {
console.log('Request failed: ' + response.status);
}
That is why you must check HTTP errors yourself. response.ok is true for success and false for failure. response.status carries the exact status code.
response.ok and response.status
When you handle HTTP errors, you use two properties together. response.ok gives a quick success check, while response.status carries the exact status code.
if (!response.ok) {
throw new Error('HTTP ' + response.status);
}
Here, if the request fails, a new Error is thrown and falls into the catch block of the async function or of the caller. This way you collect errors in one place and show the user a meaningful message. With throw, the promise is rejected.
Exercise Catch a failed request and throw
The url variable holds an address. Use await fetch(url) to put the response into a response variable. If !response.ok, throw with throw new Error('HTTP ' + response.status). Then log the text 'OK' with console.log.
Show example solution
const response = await fetch(url);
if (!response.ok) {
throw new Error('HTTP ' + response.status);
}
console.log('OK');
Test yourself
-
Catch a failed request
const response = await fetch(url);
if (____) {
throw new Error('HTTP ' + response.status);
}
Show answer
const response = await fetch(url);
if (!response.ok) {
throw new Error('HTTP ' + response.status);
}
-
What does fetch do when the server returns 404?
const response = await fetch(url);
console.log(response.ok);
- The promise is rejected
- The promise resolves, response.ok is false
- fetch throws
- response is undefined
Show answer
The promise resolves, response.ok is false — Correct! fetch does not reject on 404; response.ok is false.
-
Match status codes to their meanings
- 200
- Successful request
- 404
- Resource not found
- 500
- Server error
Next lesson: Summary - Fetch API