File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import {
2+ ArgumentsHost ,
3+ Catch ,
4+ ExceptionFilter ,
5+ HttpException ,
6+ HttpStatus ,
7+ Logger ,
8+ } from '@nestjs/common' ;
9+ import { Response } from 'express' ;
10+
11+ // Nest doesn't report errors in dev, so we do it ourselves.
12+ @Catch ( )
13+ export class ErrorFilter implements ExceptionFilter {
14+ private readonly logger = new Logger ( ErrorFilter . name ) ;
15+ private readonly bare = process . env [ 'NODE_ENV' ] === 'production' ;
16+
17+ catch ( exception : unknown , host : ArgumentsHost ) : void {
18+ const response = host . switchToHttp ( ) . getResponse < Response > ( ) ;
19+
20+ if ( exception instanceof HttpException ) {
21+ response . status ( exception . getStatus ( ) ) . json ( exception . getResponse ( ) ) ;
22+ return ;
23+ }
24+
25+ const error = exception instanceof Error ? exception : undefined ;
26+
27+ this . logger . error ( {
28+ msg : 'Request failed: {error}' ,
29+ error : error ?. message ?? String ( exception ) ,
30+ err : error ,
31+ } ) ;
32+
33+ response . status ( HttpStatus . INTERNAL_SERVER_ERROR ) . json ( {
34+ statusCode : HttpStatus . INTERNAL_SERVER_ERROR ,
35+ message : this . bare
36+ ? 'Internal server error'
37+ : ( error ?. message ?? String ( exception ) ) ,
38+ ...( this . bare ? { } : { stack : error ?. stack ?. split ( '\n' ) } ) ,
39+ } ) ;
40+ }
41+ }
Original file line number Diff line number Diff line change @@ -9,6 +9,7 @@ import 'reflect-metadata';
99import { AppModule } from './app/app.module' ;
1010import { CorsConfigModule } from './app/cors.module' ;
1111import { DocsModule } from './app/docs.module' ;
12+ import { ErrorFilter } from './app/error.filter' ;
1213
1314async function bootstrap ( ) {
1415 process . env [ 'TZ' ] = 'UTC' ;
@@ -40,6 +41,8 @@ async function bootstrap() {
4041 transform : true ,
4142 } ) ,
4243 ) ;
44+ app . useGlobalFilters ( new ErrorFilter ( ) ) ;
45+
4346 DocsModule . setupSwagger ( app ) ;
4447
4548 app . enableCors ( corsConfig . createCorsOptions ( ) ) ;
You can’t perform that action at this time.
0 commit comments