Implement Centralized Error Handling

Create src/middleware/error.middleware.js.

Express error middleware receives four arguments:

(err, req, res, next)

It should be registered after all routes.

The middleware should distinguish operational errors from unexpected internal failures.

During production, avoid exposing stack traces, database internals, or secrets to clients.

Never Leak Internal Errors

Database connection strings, secrets, stack traces, and internal infrastructure details must not be exposed through production API responses.

src/middleware/error.middleware.js
export function errorHandler(error, req, res, next) {
  console.error(error);

  if (res.headersSent) {
    return next(error);
  }

  const statusCode = error.statusCode || 500;
  const isProduction = process.env.NODE_ENV === 'production';

  res.status(statusCode).json({
    success: false,
    message:
      statusCode === 500 && isProduction
        ? 'Internal server error'
        : error.message || 'Something went wrong',
    ...(isProduction ? {} : { stack: error.stack })
  });
}

Provides a consistent error response and hides internal stack traces in production.

Key Takeaways
  • Express error middleware uses four parameters.

  • Register it after application routes.

  • Hide internal details in production.