Skip to content
Snippets Groups Projects
Commit 6ba1be14 authored by Lukáš Kratochvíl's avatar Lukáš Kratochvíl
Browse files

feat: added prisma client exception filter - specific HTTP responses

parent 188bba12
No related branches found
No related tags found
No related merge requests found
import { ArgumentsHost, Catch, HttpStatus } from '@nestjs/common';
import { BaseExceptionFilter } from '@nestjs/core';
import { Prisma } from '@prisma/client';
import { Response } from 'express';
@Catch(Prisma.PrismaClientKnownRequestError)
export class PrismaClientExceptionFilter extends BaseExceptionFilter {
catch(
exception: Prisma.PrismaClientKnownRequestError,
host: ArgumentsHost,
): void {
const context = host.switchToHttp();
const response = context.getResponse<Response>();
switch (exception.code) {
case 'P2002':
// 409 error code when unique constraint violated
const statusCode = HttpStatus.CONFLICT;
const message = exception.message.replace(/\n/g, '');
response.status(statusCode).json({
statusCode,
message, // TODO: check the message if it does not expose more info than necessary
});
break;
// TODO: other exception codes?
default:
// default 500 error code
super.catch(exception, host);
break;
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment