forked from ZyntariHQ/Invoisio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp-exception.filter.ts
More file actions
50 lines (43 loc) · 1.36 KB
/
Copy pathhttp-exception.filter.ts
File metadata and controls
50 lines (43 loc) · 1.36 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
import {
ArgumentsHost,
Catch,
ExceptionFilter,
HttpException,
HttpStatus,
} from "@nestjs/common";
import { Response } from "express";
import { RequestContextService } from "./request-context.service";
import { StructuredLogger } from "./structured-logger.service";
@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
constructor(
private readonly requestContext: RequestContextService,
private readonly logger: StructuredLogger,
) {}
catch(exception: unknown, host: ArgumentsHost): void {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const status =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
const message =
exception instanceof HttpException
? exception.getResponse()
: "Internal server error";
const correlationId = this.requestContext.getCorrelationId();
this.logger.error("http.exception", {
statusCode: status,
error: typeof message === "string" ? message : JSON.stringify(message),
});
response.status(status).json({
error:
typeof message === "string"
? message
: (message as { message?: string }).message ||
"Internal server error",
correlationId,
traceId: this.requestContext.getTraceId(),
});
}
}