From 6f803827730cf92de26d4529b0d4e4cf0dd4d906 Mon Sep 17 00:00:00 2001 From: Jaehyeon Kim <65964601+Jaehyeon1020@users.noreply.github.com> Date: Sun, 22 Sep 2024 12:55:35 +0000 Subject: [PATCH] feat(be): handle prisma exception in global exception filter --- apps/backend/libs/exception/src/filter.ts | 28 ++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/apps/backend/libs/exception/src/filter.ts b/apps/backend/libs/exception/src/filter.ts index 4f33f9839c..8f86fa2210 100644 --- a/apps/backend/libs/exception/src/filter.ts +++ b/apps/backend/libs/exception/src/filter.ts @@ -3,10 +3,15 @@ import { type ArgumentsHost, Logger, HttpException, - InternalServerErrorException + InternalServerErrorException, + ConflictException, + NotFoundException, + BadRequestException, + UnprocessableEntityException } from '@nestjs/common' import { BaseExceptionFilter } from '@nestjs/core' import type { GqlExceptionFilter } from '@nestjs/graphql' +import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library' import { BusinessException } from './business.exception' @Catch() @@ -17,6 +22,9 @@ export class AdminExceptionFilter implements GqlExceptionFilter { if (exception instanceof BusinessException) { this.logger.log(exception) return exception.convert2HTTPException() + } else if (exception instanceof PrismaClientKnownRequestError) { + this.logger.log(exception) + return convertPrismaError2HttpException(exception) } else if (exception instanceof HttpException) { this.logger.log(exception) return exception @@ -34,6 +42,9 @@ export class ClientExceptionFilter extends BaseExceptionFilter { if (exception instanceof BusinessException) { this.logger.log(exception) super.catch(exception.convert2HTTPException(), host) + } else if (exception instanceof PrismaClientKnownRequestError) { + this.logger.log(exception) + super.catch(convertPrismaError2HttpException(exception), host) } else if (exception instanceof HttpException) { this.logger.log(exception) super.catch(exception, host) @@ -43,3 +54,18 @@ export class ClientExceptionFilter extends BaseExceptionFilter { } } } + +const convertPrismaError2HttpException = ( + exception: PrismaClientKnownRequestError +) => { + switch (exception.code) { + case 'P2002': + return new ConflictException(exception.message) + case 'P2025': + return new NotFoundException(exception.message) + case 'P2003': + return new UnprocessableEntityException(exception.message) + default: + return new BadRequestException(exception.message) + } +}