Error-handling Middleware: Error-handling middleware is used to handle errors that occur during the request-response cycle. It’s defined using middleware functions with four parameters (err
, req
, res
, next
) and is typically placed at the end of the middleware chain.
Example: Error-handling middleware
const express = require('express');
const app = express();
app.get('/', (req, res) => {
throw new Error('An error occurred');
});
// Error-handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});