From the course: Learning Node.js

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Try/catch

Try/catch - Node.js Tutorial

From the course: Learning Node.js

Start my 1-month free trial

Try/catch

- [Instructor] We got a taste of handling errors with callbacks and promises in the previous chapter with the error parameter and the catch function. We will now look at a more generic form of handling errors and exceptions with a try-catch block. This works with async/await as well which is nice since it makes the code look a lot more synchronous and easy to read. So to do that, let's go to the top of our app.post function above line 28 and type in try and then add in a trycatch statement template. If your editor does not have this, you can just type it in manually. Then let's copy all the code that is not commented between line 35 and line 48 on my screen and let's paste it inside the try block. Then let's copy the code that we had in our original catch and move it into the new catch block and then uncomment it. And then I'll get rid of the commented code. We can test out the catch functionality by creating a throw at the top of our block. So let's go to the top of our try block and…

Contents