diff --git a/backend/src/middleware/errorHandler.ts b/backend/src/middleware/errorHandler.ts new file mode 100644 index 0000000..8515949 --- /dev/null +++ b/backend/src/middleware/errorHandler.ts @@ -0,0 +1,33 @@ +import type { ErrorRequestHandler } from 'express'; +import { ZodError } from 'zod'; + +export class HttpError extends Error { + status: number; + code: string; + + constructor(status: number, code: string, message: string) { + super(message); + this.status = status; + this.code = code; + } +} + +export const notFoundHandler = () => { + throw new HttpError(404, 'NOT_FOUND', 'Not found'); +}; + +export const errorHandler: ErrorRequestHandler = (err, _req, res, _next) => { + if (err instanceof ZodError) { + res.status(400).json({ + error: 'Validation failed', + code: 'VALIDATION_ERROR', + details: err.flatten(), + }); + return; + } + + const status = err instanceof HttpError ? err.status : 500; + const code = err instanceof HttpError ? err.code : 'INTERNAL_ERROR'; + const message = status === 500 ? 'Internal server error' : err.message; + res.status(status).json({ error: message, code }); +};