Get a Quote Right Now

Edit Template

Error-handling Middleware

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');
});

Share

Leave a Reply

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