CodeBlanks Logo Icon CodeBlanks

Error handling

Learn fetch error handling.

What is error handling?

Network requests can fail: the server is unreachable, the URL is wrong, the network is down. So you wrap fetch calls in a try/catch block. The request runs in the try block; if there is an error the catch block runs.

Example: try { const res = await fetch(url); } catch (error) { console.log(error); }. If fetch errors, execution jumps to catch and the error parameter carries the error. But note: fetch only rejects on a network error. For HTTP error statuses like 404 or 500 fetch does not reject; the response still arrives. So you also need to check response.ok. If response.ok is true the status code is in the 200-299 range.

Practice Write fetch with try/catch

Write an async function safeLoad. In a try block assign await fetch("https://api.example.com/users") to const response. In a catch (error) block call console.log(error).

Starter code

App.js
// Write async function safeLoad
// in try block get response with await fetch
// in the error block log the error

Sample solution

App.js
async function safeLoad() {
  try {
    const response = await fetch("https://api.example.com/users");
  } catch (error) {
    console.log(error);
  }
}

Showing errors to the user

When an error is caught it is important to inform the user. In React you put the error into state and show it on screen. Example: const [error, setError] = useState(null); in the catch block setError("Failed to load data").

The error message should be short and clear; do not show technical details to the user. It is also common to keep a loading state: const [loading, setLoading] = useState(false). Set setLoading(true) when the request starts and setLoading(false) when it ends. This way you can draw a loading indicator. The three states work together: data, loading, error. These form the basis of a data loading flow.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When does fetch reject?

App.js
try { await fetch(url); } catch (error) { /* ... */ }
  • Never
  • On every HTTP error (e.g. 404)
  • If the response isn't JSON
  • Only on a network error Correct answer

Explanation: fetch only rejects on a network error; HTTP errors need response.ok.

2 Write the HTTP error check

Question
if (!____) throw new Error("HTTP hatası");
Answer
if (!response.ok) throw new Error("HTTP hatası");

Explanation: response.ok false means there is an HTTP error.

3 Match the concept to its role

Term Meaning
try Request block
catch Catches errors
response.ok HTTP success
loading Loading state

All lessons in Intermediate