Use a Middleware

Once you have a set of custom errors, you can configure centralized error handling. You want to have a middleware that catches all errors. There you can decide what to do with them and where to send them if they need to notify you via an alert notification.

In your API routes you’ll end up using the next() function to forward errors to the error handler middleware.

Let me show you.‘/user’, async (req, res, next) => {
try {
const newUser = User.create(req.body)
} catch (error) {

The next() function is a special function in Express.js middlewares that sends values down the middleware chain. At the bottom of your routes files you should have a .use() method that uses the error handler middleware function.

const { logError, returnError } = require(‘./errorHandler’)

The error handler middleware should have a few key parts. You should check if the error is operational, and decide which errors to send as alert notifications so you can debug them in more detail. Here’s what I suggest you add to your error handler.

function logError (err) {

function logErrorMiddleware (err, req, res, next) {

function returnError (err, req, res, next) {
res.status(err.statusCode || 500).send(err.message)

function isOperationalError(error) {
if (error instanceof BaseError) {
return error.isOperational
return false

module.exports = {