eletrotupi / tcc/ api/src/middleware/errorHandler.tsec834db7af26c3f993f9ef96ee20860b8e46c8a0
949 B | 31 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
  if (process.env.NODE_ENV === "development") {
12
    // TODO: Rig some improved, centralized error logging here
13
    console.error(`[ErrorHandler]: ${err}`);
14
  }
15

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

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

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