eletrotupi / tcc/ api/src/middleware/errorHandler.tsc901c35af9c84b6a29e5185545ced1129f33b8f4
832 B | 28 lines Raw
1
import { Request, Response, NextFunction } from 'express';
2
import { Prisma } from '@prisma/client' // Bleh
3
import { isDomainError } from "@app/lib/errors/base";
4

5
export const errorHandler = (
6
  err: unknown,
7
  req: Request,
8
  res: Response,
9
  _next: NextFunction
10
) => {
11
  req.log.error({ err }, "request failed");
12

13
  if (isDomainError(err)) {
14
    return res.status(err.status)
15
      .json({ error: err.message });
16
  }
17

18
  // Prisma errors as a fallback (or map these to domain errors in the repo)
19
  if (err instanceof Prisma.PrismaClientKnownRequestError) {
20
    if (err.code === "P2025") return res.status(404)
21
      .json({ error: "Record not found" });
22

23
    if (err.code === "P2002") return res.status(409)
24
      .json({ error: "Unique constraint violation" });
25
  }
26
  
27
  res.status(500).json({ error: "Internal server error" });
28
}