Skip to content

Commit

Permalink
chore: improve prisma exception filter messages (#18227)
Browse files Browse the repository at this point in the history
* chore: improve prisma exception filter messages

* fixup! chore: improve prisma exception filter messages
  • Loading branch information
ThyMinimalDev authored Dec 17, 2024
1 parent 5293a5c commit a0ce42e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
38 changes: 35 additions & 3 deletions apps/api/v2/src/filters/prisma-exception.filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,13 @@ import {
} from "@prisma/client/runtime/library";
import { Request } from "express";

import { ERROR_STATUS, INTERNAL_SERVER_ERROR } from "@calcom/platform-constants";
import {
BAD_REQUEST,
CONFLICT,
ERROR_STATUS,
INTERNAL_SERVER_ERROR,
NOT_FOUND,
} from "@calcom/platform-constants";
import { Response } from "@calcom/platform-types";

type PrismaError =
Expand Down Expand Up @@ -43,11 +49,37 @@ export class PrismaExceptionFilter implements ExceptionFilter {
method: request.method,
requestId,
});
response.status(HttpStatus.INTERNAL_SERVER_ERROR).json({

let message = "There was an error, please try again later.";
let statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
let errorCode = INTERNAL_SERVER_ERROR;
if (error instanceof PrismaClientKnownRequestError) {
switch (error.code) {
case "P2002": // Unique constraint failed
errorCode = CONFLICT;
statusCode = HttpStatus.CONFLICT;
message = "Invalid Input: Trying to create a record that already exists.";
break;
case "P2025": // Record not found
errorCode = NOT_FOUND;
statusCode = HttpStatus.NOT_FOUND;
message = "Invalid Query: The requested record was not found.";
break;
case "P2003": // Foreign key constraint failed
errorCode = BAD_REQUEST;
statusCode = HttpStatus.BAD_REQUEST;
message = "Invalid input: The referenced data does not exist.";
break;
default:
break;
}
}

response.status(statusCode).json({
status: ERROR_STATUS,
timestamp: new Date().toISOString(),
path: request.url,
error: { code: INTERNAL_SERVER_ERROR, message: "There was an error, please try again later." },
error: { code: errorCode, message: message },
});
}
}
1 change: 1 addition & 0 deletions packages/platform/constants/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export const METHOD_NOT_ALLOWED = "METHOD_NOT_ALLOWED";
export const UNPROCESSABLE_ENTITY = "UNPROCESSABLE_ENTITY";
export const ACCESS_TOKEN_EXPIRED = "ACCESS_TOKEN_IS_EXPIRED";
export const INVALID_ACCESS_TOKEN = "Invalid Access Token.";
export const CONFLICT = "CONFLICT";

// Server Errors (5xx)
export const INTERNAL_SERVER_ERROR = "INTERNAL_SERVER_ERROR";
Expand Down

0 comments on commit a0ce42e

Please sign in to comment.