0
0
Expressframework~5 mins

Error-handling middleware in Express

Choose your learning style9 modes available
Introduction

Error-handling middleware helps catch and respond to errors in your app. It keeps your app from crashing and shows friendly messages.

When you want to catch errors from routes or other middleware.
When you want to send a custom error message to users.
When you want to log errors for debugging.
When you want to handle 404 or other HTTP errors gracefully.
Syntax
Express
app.use(function (err, req, res, next) {
  // handle the error here
});

Error-handling middleware always has four parameters: err, req, res, and next.

It must be added after all other app.use() and routes.

Examples
Sends a simple 500 error message when an error happens.
Express
app.use(function (err, req, res, next) {
  res.status(500).send('Something broke!');
});
Logs the error stack to the console and sends a JSON error message.
Express
app.use(function (err, req, res, next) {
  console.error(err.stack);
  res.status(500).json({ error: err.message });
});
Sample Program

This app throws an error when you visit the home page. The error-handling middleware catches it, logs it, and sends a custom message to the browser.

Express
import express from 'express';
const app = express();

app.get('/', (req, res) => {
  throw new Error('Oops!');
});

// Error-handling middleware
app.use((err, req, res, next) => {
  console.error('Error caught:', err.message);
  res.status(500).send('Custom error: ' + err.message);
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Always place error-handling middleware last, after all routes.

Use next(err) in routes or middleware to pass errors to this handler.

Sending detailed error info to users is okay in development but avoid it in production for security.

Summary

Error-handling middleware catches errors and prevents crashes.

It has four parameters: err, req, res, next.

Place it after all other middleware and routes.