Try sending a POST request to create a Github repository. If you donโt provide any authentication, youโll get an error from the Github. It says 401 Unauthorized.
// With XHRconst request = new XMLHttpRequest()request.open('post', 'https://api.github.com/user/repos')request.send()
// With Fetchfetch('https://api.github.com/user/repos', { method: 'post' })
This is one reason why an error may occur.
Why errors occur
Errors can occur for many reasons. The error message you get will differ according to the type of error. When working with APIs, youโll usually get 400 errors.
The common ones are:
400 Bad requestโthis happens for many reasons. Itโs the most common type of error. Usually, this happens because your request didnโt contain required fields.401 Unauthorizedโthis happens because you are not authenticated. It also happens if youโre not authorized to perform an action.403 Forbiddenโthis happens because the server refuses to act on your action. Hereโs an example: when you hit your rate limit, youโll get a forbidden response.404 Not foundโthis happens because you tried to fetch a nonexistent request.405 Method not allowedโthis happens because you used a wrong method.
Why deal with errors
Nobody likes to receive an error. What people hate even more is an error tells them to try again without saying whatโs wrong.
You want to provide useful error messages. When you do so, the user can fix the error immediately.
If you donโt know whatโs wrong, the least you can do is tell your user to contact you with more information. When they send you info, you can help them overcome the error.
Dealing with XHR errors
First, you want to know if you received an error. To do so, you can check the status. If the status is larger than 400, you know you received an error.
request.addEventListener('load', e => { const response = e.target if (response.status >= 400) { // Handle error here }})When you get an error, the server will also send information about the error. This information is usually found in the response body.
request.addEventListener('load', e => { const response = e.target if (response.status >= 400) { const error = JSON.parse(response.response) console.log(error) }})
You can handle the error based on what the server sends back to you. In this case, you can do one of the following:
- Direct a user to login with their username and password.
- Tell the user they entered the username or password incorrectly.
Dealing with Fetch errors
When you use Fetch, you also need to check if the server sends you an error message. You can do it through two ways:
- Checking
statusis larger than 400 - Checking
okis true
The ok property is unique to Fetch. It is set to false if status is larger than 400
fetch('https://api.github.com/user/repos').then(response => { if (response.ok) return response.json() // Handle error here})When we use a Promise, we handle errors in the .catch call. Since Fetch is a Promise, we need to send the error into the .catch call ourselves.
We can do this by calling Promise.reject.
fetch('https://api.github.com/user/repos').then(response => { if (response.ok) return response.json() Promise.reject(/* Argument to pass to catch */)})We have a slight problem hereโresponse.json returns a promise. We cannot send response.json via Promise.reject. We need to resolve it first.
The complete fetch request should look like this:
fetch('https://api.github.com/user/repos') .then(response => { return response.json().then(body => { if (response.ok) return body return Promise.reject({ body }) }) }) .then(body => console.log(`body is `, body)) .catch(error => console.log(`error is`, error))
Exercise
- Send an XHR request that results in an error. Handle the error.
- Send a Fetch request that results in an error. Handle the error.
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