diff --git a/src/app.module.ts b/src/app.module.ts index 1c5a00a6..f59b7c7c 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -7,6 +7,8 @@ import { TestRunsModule } from './test-runs/test-runs.module'; import { TestVariationsModule } from './test-variations/test-variations.module'; import { PrismaService } from './prisma/prisma.service'; import { ConfigModule } from '@nestjs/config'; +import { APP_FILTER } from '@nestjs/core'; +import { HttpPrismaExceptionFilter } from './http-prisma-exception.filter'; @Module({ imports: [ @@ -18,6 +20,12 @@ import { ConfigModule } from '@nestjs/config'; TestRunsModule, TestVariationsModule, ], - providers: [PrismaService], + providers: [ + PrismaService, + { + provide: APP_FILTER, + useClass: HttpPrismaExceptionFilter, + }, + ], }) export class AppModule {} diff --git a/src/http-prisma-exception.filter.ts b/src/http-prisma-exception.filter.ts new file mode 100644 index 00000000..ac2b0f44 --- /dev/null +++ b/src/http-prisma-exception.filter.ts @@ -0,0 +1,20 @@ +import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common'; +import { Request, Response } from 'express'; +import { PrismaClientKnownRequestError } from '@prisma/client'; + +@Catch(PrismaClientKnownRequestError) +export class HttpPrismaExceptionFilter implements ExceptionFilter { + catch(exception: PrismaClientKnownRequestError, host: ArgumentsHost) { + const ctx = host.switchToHttp(); + const response = ctx.getResponse(); + const request = ctx.getRequest(); + + response.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ + stack: exception.stack, + message: exception.message, + code: exception.code, + timestamp: new Date().toISOString(), + path: request.url, + }); + } +} diff --git a/src/users/users.service.ts b/src/users/users.service.ts index 1e4f13a8..4256d0af 100644 --- a/src/users/users.service.ts +++ b/src/users/users.service.ts @@ -25,19 +25,11 @@ export class UsersService { password: await this.authService.encryptPassword(createUserDto.password), }; - try { - const userData = await this.prismaService.user.create({ - data: user, - }); - - return new UserLoginResponseDto(userData, null); - } catch (err) { - if (err.original.constraint === 'user_email_key') { - throw new HttpException(`User with email '${err.errors[0].value}' already exists`, HttpStatus.CONFLICT); - } + const userData = await this.prismaService.user.create({ + data: user, + }); - throw new HttpException(err, HttpStatus.INTERNAL_SERVER_ERROR); - } + return new UserLoginResponseDto(userData, null); } async findOne(id: string): Promise {