Member-only story
Simplify your code by using an error handling middleware
Due to the unopinionated nature of JavaScript, there are many ways to accomplish a single task. This can be a double edge sword, especially when working in a larger team setting. This is where processes and guidelines come into play. In this article I’m going to show you how my team does error handling in an Express.js application using an error handling middleware.
Prerequisites
- Node.js installed on your machine
- Knowledge of Node.js and Express.js
- Knowledge of how middleware works in Express.js
Project Setup
Let’s create a basic Express.js application with one endpoint. The endpoint is a POST
method that takes two input parameters, title
and author
.
We check if title
and author
exist, if not we throw a 400 error and send back a JSON with status and message.
If title
and author
exist, the app will still crash because db
is not defined and our try/catch block will catch it and send back a 500 error and JSON with status and message.
Over time, as your endpoints and validations grow organically, typing out res.status(4xx).json({ some: JSON })
every time can get cumbersome quickly and also create a lot of code redundancy. Wouldn’t it be nice to do something like throw new BadRequest('message')
? Let’s see how we can accomplish that.
Create errors utils
Now let’s start by creating a utility function we can use to throw errors. Create a new folder /utils
and file errors.js
.
This file defines what errors we can throw in our application. The GeneralError
class…