Skip to content

Commit a63502e

Browse files
committed
added global error filter
1 parent 99811d6 commit a63502e

2 files changed

Lines changed: 44 additions & 0 deletions

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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+
}

packages/api/src/main.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import 'reflect-metadata';
99
import { AppModule } from './app/app.module';
1010
import { CorsConfigModule } from './app/cors.module';
1111
import { DocsModule } from './app/docs.module';
12+
import { ErrorFilter } from './app/error.filter';
1213

1314
async 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());

0 commit comments

Comments
 (0)