Centralized Error Handling
On this page
Why Centralization Matters
Scattered try/catch blocks lead to inconsistent responses and missing logs. A centralized error handler enforces one error shape and one logging strategy.
Error Translation Layer
Your error handler should translate internal exceptions into safe client-facing errors. This protects sensitive details and ensures monitoring tools receive structured signals.
Example Pattern
function errorHandler(err, req, res, next) {
const requestId = req.requestId;
console.error({ requestId, err });
res.status(500).json({
error: { code: 'INTERNAL_ERROR', message: 'Unexpected error', requestId }
});
}
Production Rules
- Register last in middleware chain
- Log before responding
- Never expose stack traces to clients
- Map known domain errors to explicit status codes