/** * Centralized Express error handler — production-safe messages and consistent status codes. */ import { Request, Response, NextFunction } from 'express'; import { clientErrorMessage } from '../utils/safeError'; import { HttpError, httpStatusForError } from '../utils/httpError'; import { captureException } from '../observability/sentry'; /** * Wraps an async route handler so rejections reach the global error middleware. */ export function asyncHandler( fn: (req: Request, res: Response, next: NextFunction) => Promise ) { return (req: Request, res: Response, next: NextFunction): void => { void fn(req, res, next).catch(next); }; } export function errorHandler( err: unknown, _req: Request, res: Response, _next: NextFunction ): void { if (res.headersSent) return; const status = httpStatusForError(err); const code = (err as { code?: string })?.code ?? (err instanceof HttpError ? err.code : undefined); if (status >= 500) { console.error(err); captureException(err); } const fallback = status >= 500 ? 'Internal server error' : 'Request failed'; const expose = err instanceof HttpError ? err.expose : status < 500; res.status(status).json({ error: expose ? clientErrorMessage(err, fallback) : fallback, ...(code ? { code } : {}), }); }