Error Handling with Promises
Learn how ES2015 solves the problem of callback hell and the Pyramid of Doom. Promises are now used everywhere in asynchronous code and are part of modern and future JavaScript.
We'll cover the following...
In this lesson, we’ll learn how to handle errors with Promises. Here’s the code we were using in the last lesson.
Press + to interact
onRequest((request, response) =>readFile(request.fileToRead, data =>writeFile(request.fileToWrite, data, status =>response.send(status))));
Let’s add error handling to this function. We’ll use a simple try
/catch
block to catch any possible errors.
Press + to interact
onRequest((request, response) => {try {readFile(request.fileToRead, data =>writeFile(request.fileToWrite, data, status =>response.send(status)));} catch(err) {console.log(err);response.send(err);}});
Here’s the Promise-enabled code we wrote last lesson.
Press + to interact
onRequest((request, response) =>readFile(request.fileToRead).then(data => writeFile(request.fileToWrite, data)).then(status => response.send(status)));
Error Handling
Asynchronous operations generally require error handling in case something goes wrong (network issues, data not found, bad request, etc.). Promises have this built-in. They can take in a second callback that handles errors. It’ll only be called in the ...
Access this course and 1400+ top-rated courses and projects.