forked from CatsMiaow/nestjs-project-structure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exceptions.filter.ts
executable file
·38 lines (34 loc) · 1.41 KB
/
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, HttpException, HttpStatus, Logger } from '@nestjs/common';
import { BaseExceptionFilter } from '@nestjs/core';
import { GqlArgumentsHost, GqlContextType, GqlExceptionFilter } from '@nestjs/graphql';
@Catch()
export class ExceptionsFilter extends BaseExceptionFilter implements GqlExceptionFilter {
private readonly logger: Logger = new Logger();
public override catch(exception: unknown, host: ArgumentsHost): void {
let args: unknown;
if (host.getType<GqlContextType>() === 'graphql') {
const gqlHost = GqlArgumentsHost.create(host);
const { req: { body: { operationName, variables } } } = gqlHost.getContext();
args = `${operationName} ${JSON.stringify(variables)}`;
} else {
super.catch(exception, host);
// const req = host.switchToHttp().getRequest<Request>();
// req.method, req.originalUrl...
// args = req.body;
}
const status = this.getHttpStatus(exception);
if (status === HttpStatus.INTERNAL_SERVER_ERROR) {
if (exception instanceof Error) {
this.logger.error(`${exception.message}: ${args}`, exception.stack);
} else {
// Error Notifications
this.logger.error('UnhandledException', exception);
}
}
}
private getHttpStatus(exception: unknown): number {
return exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
}
}