Centralized Error Handling

Express applications should use centralized error handling instead of duplicating response logic throughout controllers. Error middleware has the signature (err, req, res, next).

Production systems should avoid exposing internal stack traces or secrets to clients. Errors should be logged with sufficient context while API responses contain safe information.

Do Not Leak Internal Errors

Never return database connection strings, access tokens, stack traces, or internal implementation details to untrusted clients.

Error Middleware
app.use((err, req, res, next) => {
  console.error(err);

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

  res.status(err.statusCode || 500).json({
    error: err.publicMessage || 'Internal server error'
  });
});
💡 The error middleware logs the internal error and returns a controlled response to the client.
Key Takeaways
  • Centralize API error responses.
  • Separate internal error details from public API messages.
  • Handle errors consistently across asynchronous operations.
Knowledge Check

What distinguishes Express error-handling middleware?