UNPKG

@ingeze/api-error

Version:

A TypeScript library for handling HTTP errors in Express, NestJS, and Fastify APIs.

50 lines (49 loc) 1.25 kB
import { ErrorHandler, ValidationError } from "../errors/index.js"; import { ZodError } from "zod"; function expressErrorMiddleware(err, req, res, next) { if (res.headersSent) { return next(err); } if (err instanceof ErrorHandler) { res.status(err.statusCode).json({ result: err.toJSON(), data: null, pagination: null }); return; } else if (err instanceof ZodError) { const fieldErrors = {}; for (const issue of err.issues) { const path = issue.path?.[0] ?? "unknown"; const msg = issue.message; if (!fieldErrors[String(path)]) { fieldErrors[String(path)] = []; } fieldErrors[String(path)].push(msg); } const validationErr = new ValidationError({ errors: fieldErrors }); res.status(validationErr.statusCode).json({ result: validationErr.toJSON(), data: null, pagination: null }); return; } else { res.status(500).json({ result: { success: false, statusCode: 500, type: "INTERNAL_SERVER_ERROR", message: "An unexpected error occurred" }, data: null, pagination: null }); } } export { expressErrorMiddleware }; //# sourceMappingURL=express.js.map