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.


app.post(‘/user’, async (req, res, next) => {
try {
const newUser = User.create(req.body)
} catch (error) {
next(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’)

app.use(logError)
app.use(returnError)
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) {
console.error(err)
}

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

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 = {
logError,
logErrorMiddleware,
returnError,
isOperationalError
}