Skip to content

Commit

Permalink
feat(be): handle prisma exception in global exception filter
Browse files Browse the repository at this point in the history
  • Loading branch information
Jaehyeon1020 committed Sep 22, 2024
1 parent a350cbc commit 6f80382
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion apps/backend/libs/exception/src/filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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
Expand All @@ -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)
Expand All @@ -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)
}
}

0 comments on commit 6f80382

Please sign in to comment.