0
0
Node.jsframework~5 mins

Centralized error handling in Node.js

Choose your learning style9 modes available
Introduction

Centralized error handling helps catch and manage errors in one place. This keeps your code clean and easier to fix problems.

When you want to handle all errors from different parts of your app in one spot.
When building a web server that needs to send friendly error messages to users.
When you want to log errors consistently for debugging.
When you want to avoid repeating error handling code everywhere.
When you want to keep your app stable by catching unexpected errors.
Syntax
Node.js
function errorHandler(err, req, res, next) {
  res.status(500).send({ error: err.message });
}

app.use(errorHandler);

This is an Express.js error middleware function with four parameters.

It must be added after all other routes and middleware.

Examples
Logs the error stack and sends a simple message to the client.
Node.js
function errorHandler(err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Something broke!');
}
app.use(errorHandler);
Sends JSON with error details only in development mode.
Node.js
function errorHandler(err, req, res, next) {
  res.status(err.status || 500).json({
    message: err.message,
    error: process.env.NODE_ENV === 'development' ? err : {}
  });
}
app.use(errorHandler);
Sample Program

This Express app throws an error on the home route. The centralized error handler catches it, logs it, and sends a JSON error message to the client.

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

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

function errorHandler(err, req, res, next) {
  console.error('Error caught:', err.message);
  res.status(500).send({ error: err.message });
}

app.use(errorHandler);

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

Always place the error handler after all routes and middleware.

Use next(err) in async code to pass errors to the handler.

Customize error responses for better user experience.

Summary

Centralized error handling keeps error code in one place.

It improves app stability and debugging.

In Express, use a middleware with four parameters for errors.