Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed REST APIs with Express!
You have completed REST APIs with Express!
Preview
Using try/catch blocks to handler errors for each route can get messy after a while. We can write a middleware function that can abstract away the try/catch block to DRY up our code.
Snippet
function asyncHandler(cb){
return async (req, res, next)=>{
try {
await cb(req,res, next);
} catch(err){
next(err);
}
};
}
- If you'd like to know more about how this function, works, review the Reduce Error Handling Code When Using Async/Await video.
- npm module for handling async/await syntax in Express
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
We can use a piece of middleware to
prevent having to use try-catch blocks for
0:00
every single route.
0:03
Into app JS, I've added a middleware
function called asynchandler.
0:04
If you're following along with me,
see the teacher's notes to copy and
0:09
paste this function.
0:12
You don't need to worry about
the exact details of how this works.
0:13
Remember, that's kind of the point of
using a helper function or a library.
0:16
It abstracts complexities away for you.
0:20
But basically, it takes in a function,
wraps it in a try-catch block,
0:22
and passes any errors to the global error
handler we wrote in the last video.
0:28
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up