forked from xhiroga/nestjs-meetup-online1-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathall-exceptions.filter.ts
38 lines (31 loc) · 1.26 KB
/
all-exceptions.filter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import {
ArgumentsHost, Catch, ExceptionFilter, HttpException,
HttpStatus
} from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import { PinoLogger } from 'nestjs-pino';
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
constructor(
private readonly httpAdapterHost: HttpAdapterHost,
private readonly logger: PinoLogger,
) { }
catch(exception: unknown, host: ArgumentsHost): void {
// In certain situations `httpAdapter` might not be available in the
// constructor method, thus we should resolve it here.
const { httpAdapter } = this.httpAdapterHost;
const ctx = host.switchToHttp();
const httpStatus =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
const responseBody = {
statusCode: httpStatus,
timestamp: new Date().toISOString(),
path: httpAdapter.getRequestUrl(ctx.getRequest()),
};
const stack = exception instanceof (HttpException || Error) ? exception.stack : null;
this.logger.error(JSON.stringify(responseBody), stack);
httpAdapter.reply(ctx.getResponse(), responseBody, httpStatus);
}
}