0
0
Node.jsframework~5 mins

Error-handling middleware in Node.js

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 clear error message to users
When you want to log errors for debugging
When you want to handle unexpected problems gracefully
When you want to keep your app running even if something goes wrong
Syntax
Node.js
app.use(function (err, req, res, next) {
  // handle the error here
  res.status(500).send('Something broke!');
});

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

It must be added after all other middleware and routes.

Examples
Logs the error stack and sends a simple error message to the client.
Node.js
app.use(function (err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Oops! Something went wrong.');
});
Handles different error types with custom messages.
Node.js
app.use(function (err, req, res, next) {
  if (err.type === 'database') {
    res.status(500).send('Database error occurred');
  } else {
    res.status(500).send('General error');
  }
});
Sample Program

This app throws an error when visiting the home page. The error-handling middleware catches it, logs it, and sends a friendly message.

Node.js
import express from 'express';
const app = express();

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

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

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

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

Use console.error to log errors for debugging.

Sending generic messages helps keep your app secure by not revealing details.

Summary

Error-handling middleware catches errors in your app.

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

Place it after all other middleware and routes to work properly.