Error handling for JS fetch requests
The following example handles server and connectivity errors for javascript fetch requests.
1function handleErrors(response) {
2 if (!response.ok) throw new Error(response.status)
3 return response
4}
5
6fetch('https://jsonplaceholder.typicode.com/todos/1')
7 // handle network err/success
8 .then(handleErrors)
9 // use response of network on fetch Promise resolve
10 .then(response => console.log("ok"))
11 // handle fetch Promise error
12 .catch(error => console.log('found an error: ', error))
handleErrors
can be updated for handling different types of errors in different ways. This function is called whenever we get a response from the server (successful or failed). When we have a different type of error, like a DNS one, the catch block is called directly.
All errors are caught by the catch section, because server errors end up in throwing a new Error instance. Such Error instance can be extended to meet specific needs.
References
- Amirmohammad Moradi. Fetch API error handling.