Express.js provides a built-in middleware function, called the error handler, which takes four arguments: err, req, res, and next.

The error handler is typically placed at the end of the middleware stack so that it can catch any errors that may have been thrown by previous middleware.

Example:

const express = require(‘express’);

const app = express();

// middleware functions
app.use(logger);
app.use(authenticator);

// error handler
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send(‘Something broke!’);
});

app.listen(3000);

Leave a Reply

Your email address will not be published. Required fields are marked *