Authentication in Node.js - #5 Error Handling

Published: 27 December 2019
on channel: Code Realm
9,322
128

Following up on our previous video about registration, we are going to implement proper error handling in this episode. Currently, any unhandled promise rejection such as the case with validation, causes the response to time out. This is because in Express, any exception thrown in an asynchronous route handler needs to be passed to next() explicitly.

We can ameliorate this with repeated try-catch blocks around asynchronous code. However, this approach doesn't scale and leads to duplication. Instead, we are going to wrap each async handler function with a wrapper function. This will tack on catch(next) to each promise chain, so in case of an exception, it gets properly forwarded to the centralized error handler. You can read up on this technique in more detail at StrongLoop https://strongloop.com/strongblog/asy...

As far as capturing 404 and 500 errors in Express, the docs, specifically the FAQ section, are very clear on this https://expressjs.com/en/starter/faq.... You can mount two middleware functions at the bottom of the stack, one to handle any unmatched routes and the other to be a catch-all for any unexpected errors (ex: failed DB queries, runtime exceptions, etc.). Just be sure to attach them to the express() and not Router() instance; otherwise, they won't get matched.

To differentiate between 4xx and 5xx errors, we will also define custom Error classes for each HTTP status code, such as 400 and 404. This will allow us to send back proper status codes and only log the stack trace of internal server errors.

More on error handling in Express https://expressjs.com/en/guide/error-...

GitHub repo https://github.com/alex996/node-auth


Watch video Authentication in Node.js - #5 Error Handling online without registration, duration hours minute second in high quality. This video was added by user Code Realm 27 December 2019, don't forget to share it with your friends and acquaintances, it has been viewed on our site 9,32 once and liked it 12 people.