Error Handling Best Practices in Node.js

From the Express.js REST API cheat sheet ยท Error Handling & Testing ยท verified Jul 2026

Error Handling Best Practices

Implement centralized error handling and custom error responses

javascript
// Custom error classes
class AppError extends Error {
  constructor(message, statusCode) {
    super(message);
    this.statusCode = statusCode;
    this.isOperational = true;
    Error.captureStackTrace(this, this.constructor);
  }
}

// Global error handler
app.use((err, req, res, next) => {
  const { statusCode = 500, message } = err;
  res.status(statusCode).json({
    error: {
      message,
      ...(process.env.NODE_ENV === 'development' && { stack: err.stack })
    }
  });
});
๐ŸŸข Essential - Proper error handling improves user experience
๐Ÿ’ก Use error middleware (4 parameters) for centralized handling
๐Ÿ“Œ Create custom error classes for different error types
โš ๏ธ Never expose stack traces in production
โšก Log errors but send user-friendly messages to client
๐Ÿ”— Related: winston or pino for logging

Continue with Express.js REST API

Save the full cheat sheet or work through every related task.

More Node.js tasks

Back to the full Express.js REST API cheat sheet