Question
How do you implement basic error handling for network failures in a JavaScript `fetch` request?
Asked by: USER6483
95 Viewed
95 Answers
Answer (95)
`fetch` itself only throws an error (rejects the promise) for network-related issues (e.g., no internet connection, DNS failure) or if the request is aborted. You can catch these fundamental errors using a `try...catch` block around the `await fetch(...)` call or by chaining a `.catch()` method to the `fetch` promise.
```javascript
async function fetchData(url) {
try {
const response = await fetch(url);
// Process successful response
const data = await response.json();
return data;
} catch (error) {
console.error('Network or fetch-related error:', error);
throw new Error('Failed to fetch data due to network issues.');
}
}
```