import type { ErrorHandlerService } from "@batch-cooking/error-tools"; import type { NextFunction, Request, Response } from "express"; /** Express error-handling middleware signature (the 4-arg form Express detects as an error handler). */ type ExpressErrorMiddleware = ( err: unknown, req: Request, res: Response, next: NextFunction, ) => void; /** * Builds the final Express error-handling middleware for an app: every * thrown/`next(err)`-ed error ends up here, gets mapped by the given * {@link ErrorHandlerService}, and sent as the response. Keeps the actual * "what does this error mean" logic in the service, testable on its own — * this factory is just the thin Express adapter. * * @example * app.use(createErrorMiddleware(errorHandlerService)); */ export function createErrorMiddleware(errorHandler: ErrorHandlerService): ExpressErrorMiddleware { return (err, _req, res, _next) => { const { status, body } = errorHandler.handle(err); res.status(status).json(body); }; }