eletrotupi / tcc/ api/src/middleware/errorHandler.ts3bcf802a5ee2d0a9efe349a6250e92f62e9f27ee
893 B | 29 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
  // TODO: Rig some improved, centralized error logging here
12
  console.error(`[ErrorHandler]: ${err}`);
13

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

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

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