Most requests are going to be successful, but some of them may fail.
When they fail, we have to catch errors from these failed requests and display an error message that makes sense.
Here’s how you do it if you’re using Promises.
fetch('http://link-to-resource') .then(response => response.json()) .then(/* do something if request is successful */) .catch(/* handle the error */)And here’s how you do it if you’re using Async functions.
try { const response = await fetch('http://link-to-resource') const data = await response.json()} catch { // Handle the error}Easier error handling with zlFetch
In zlFetch you have the option to return the error by setting returnError to true.
You can use this inside an Async function without using the try/catch block.
const { response, error } = await fetch('http://link-to-resource', { returnError: true})
if (response) { /* Do something with the response */ }if (error) { /* Do something with the error */ }A real example
Let’s say a user entered the wrong password into a form and the server returned a 401 Unauthorised error.
This simply means the username or password is wrong.
You can take the error message and display it on the form so users know exactly what’s going on.
const form = document.querySelector('form')const errorDiv = form.querySelector('errorDiv')
form.addEventListener('submit', async event => { const { response, error } = await zlFetch.post('http://link-to-resource')
if (response) { // Do something with response }
// Display the error message if (error) { const errorMessage = error.body.message errorDiv.textContent = errorMessage }})This example shows you how to use the error message returned from the server.
If the message doesn’t make sense, you should craft an error message that makes more sense!
Next, let’s talk about reading API documentation.
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson