1+ import {
2+ ExceptionFilter ,
3+ Catch ,
4+ ArgumentsHost ,
5+ HttpStatus ,
6+ Logger ,
7+ } from '@nestjs/common' ;
8+ import { Request , Response } from 'express' ;
9+ import { Prisma } from '@prisma/client' ;
10+
11+ @Catch ( Prisma . PrismaClientKnownRequestError )
12+ export class PrismaExceptionFilter implements ExceptionFilter {
13+ private readonly logger = new Logger ( PrismaExceptionFilter . name ) ;
14+
15+ catch ( exception : Prisma . PrismaClientKnownRequestError , host : ArgumentsHost ) {
16+ const ctx = host . switchToHttp ( ) ;
17+ const response = ctx . getResponse < Response > ( ) ;
18+ const request = ctx . getRequest < Request > ( ) ;
19+
20+ let status = HttpStatus . INTERNAL_SERVER_ERROR ;
21+ let message = 'Database error occurred' ;
22+ let errors = null ;
23+
24+ // Handle common Prisma errors
25+ switch ( exception . code ) {
26+ case 'P2002' : // Unique constraint violation
27+ status = HttpStatus . CONFLICT ;
28+ const target = ( exception . meta ?. target as string [ ] ) ?. join ( ', ' ) || 'field' ;
29+ message = `Unique constraint failed on ${ target } ` ;
30+ errors = { [ target ] : 'must be unique' } ;
31+ break ;
32+ case 'P2025' : // Record not found
33+ status = HttpStatus . NOT_FOUND ;
34+ message = 'Record not found' ;
35+ break ;
36+ case 'P2003' : // Foreign key constraint violation
37+ status = HttpStatus . BAD_REQUEST ;
38+ message = 'Foreign key constraint failed - related record does not exist' ;
39+ break ;
40+ case 'P2014' : // Relation violation
41+ status = HttpStatus . BAD_REQUEST ;
42+ message = 'Invalid relation - cannot change record due to existing dependencies' ;
43+ break ;
44+ case 'P2000' : // Value too long for column
45+ status = HttpStatus . BAD_REQUEST ;
46+ message = 'Value too long for column' ;
47+ break ;
48+ case 'P2011' : // Null constraint violation
49+ status = HttpStatus . BAD_REQUEST ;
50+ message = 'Null constraint violation - cannot set required field to null' ;
51+ break ;
52+ default :
53+ this . logger . error ( `Unhandled Prisma error: ${ exception . code } ` , exception . stack ) ;
54+ }
55+
56+ this . logger . error (
57+ `Prisma Exception: ${ exception . code } - ${ message } - ${ request . url } - Stack: ${ exception . stack } ` ,
58+ ) ;
59+
60+ response . status ( status ) . json ( {
61+ success : false ,
62+ statusCode : status ,
63+ timestamp : new Date ( ) . toISOString ( ) ,
64+ path : request . url ,
65+ message,
66+ errors,
67+ prismaCode : process . env . NODE_ENV === 'development' ? exception . code : undefined ,
68+ stack : process . env . NODE_ENV === 'development' ? exception . stack : undefined ,
69+ } ) ;
70+ }
71+ }
0 commit comments