Take a look at this code:
fetch('/profile')
.then(data => {
if (data.status === 200) {
return data.json()
}
throw new Error("Unable to get Profile.")
})
.then(json => {
console.log(json)
})
.catch(error => {
alert(error)
})
We have some of the usual suspects here: a fetch call and .then() handling our results. Now, take a look at new Error() and .catch(). Just like in most languages, JavaScript has a way to explicitly throw errors, and .catch() at the end of our fetch chain will then present the error to the user in an alert box. It's always best practice to include error handling in your Ajax calls in case the service you're calling doesn't respond, doesn't respond in time, or sends back an error. We'll discuss errors a bit more in Chapter 9, Deciphering Error Messages and Performance Leaks.