Authentication in Node.js – #5 Error Handling

テクノロジー



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/async-error-handling-expressjs-es7-promises-generators/

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.html#how-do-i-handle-404-responses 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-handling.html

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

Comments

Copied title and URL