React Native
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.
Exercise 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).
Show example solution
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.
Test yourself
-
When does fetch reject?
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
Show answer
Only on a network error — fetch only rejects on a network error; HTTP errors need response.ok.
-
Write the HTTP error check
if (!____) throw new Error("HTTP hatası");
Show answer
if (!response.ok) throw new Error("HTTP hatası");
-
Match the concept to its role
- try
- Request block
- catch
- Catches errors
- response.ok
- HTTP success
- loading
- Loading state
Next lesson: Summary - API and fetch