Drop me a DM, and let's chat! :)
Last weekend I had the pleasure to visit Tokyo and gave a talk at the amazing nodefest conference, titled Node.js Production Checklist. The talk was dedicated to topics like error handling, monitoring and logging best practices, as well as incident handling. If you interested in all the slides, you can find it on Speakerdeck.
In this blog post you will learn about how you can handle errors in Express applications.
Tokyo in pictures
You can find a lot of amazing gardens in Tokyo - they are the perfect locations to get away a bit and get some fresh air.
Tokyo is one of the world’s most exciting dining destinations.
Oh, and the city never sleeps!
One of the most crucial things to get right when building web applications are error handling. As the system will depend on other services, databases, as well as consumers of those services, the unexpected becomes expected. Databases will fail, services become unavailable and your consumers won’t be calling your endpoints with the parameters you expect.
To prepare your application for such circumstances, you have to handle errors properly. Let’s take a look at the following endpoint:
The endpoint above has some serious flaws:
- it handles errors in different parts of the codebase,
- it does not use Express’ error handler to have a unified error handling logic.
Let’s see how you can fix these issues! 👌
All Express route handlers come with a third function parameter,
next, which can be used to call the next middleware, or to signal Express that an error happened:
This way you’ve already let Express know that an error arose, and the error handler will get called. To add an error handler to your application, you have to add a middleware with four parameters - that’s how Express will know it is an error handler.
Even if this solution works, it adds a lot of boilerplate code - let’s get rid of that!
boom is an HTTP-friendly error object, that provides you helpers for standard HTTP errors:
To make sure we return with the newly created status codes and errors, you have to update the error handler to use properties from boom errors:
If you’d like to use async-await in your Express route handlers, you have to do the following:
- create a wrapper for the async functions, so errors are propagated
- instead of calling
nextin your route handlers, simply throw.