Skip to content

Node.js – Error Handling

Rules

  • Create a centralized Express error handling middleware
  • Define a custom AppError class with statusCode and isOperational
  • Never expose stack traces to API responses in production
  • Always handle unhandledRejection and uncaughtException

AppError Class

class AppError extends Error {
  constructor(message, statusCode) {
    super(message);
    this.statusCode = statusCode;
    this.isOperational = true;
  }
}

Centralized Error Handler

app.use((err, req, res, next) => {
  const statusCode = err.statusCode || 500;
  res.status(statusCode).json({
    error: err.isOperational ? err.message : 'Internal server error'
  });
});

Process Level Handlers

process.on('unhandledRejection', (err) => {
  console.error('Unhandled Rejection:', err);
  process.exit(1);
});

process.on('uncaughtException', (err) => {
  console.error('Uncaught Exception:', err);
  process.exit(1);
});