forked from digikare/nestjs-prom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prom-catch-all.exception-filter.ts
70 lines (57 loc) · 1.83 KB
/
prom-catch-all.exception-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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { Catch, ArgumentsHost, ExecutionContext, HttpException, HttpStatus } from "@nestjs/common";
import { BaseExceptionFilter } from '@nestjs/core';
import { GqlContextType, GqlExecutionContext } from '@nestjs/graphql'
import { CounterMetric } from "./interfaces";
import { normalizePath } from './utils';
import { PromService } from './prom.service';
function getBaseUrl(url?: string) {
if (!url) {
return url;
}
if (url.indexOf('?') === -1) {
return url;
}
return url.split('?')[0];
}
@Catch()
export class PromCatchAllExceptionsFilter extends BaseExceptionFilter {
private readonly _counter: CounterMetric;
constructor(
promService: PromService,
) {
super();
this._counter = promService.getCounter({
name: 'http_exceptions',
labelNames: ['method', 'status', 'path'],
});
}
catch(
exception: unknown,
host: ArgumentsHost,
) {
const isGraphQLRequest = host.getType<GqlContextType>() === 'graphql'
const request = isGraphQLRequest
? GqlExecutionContext.create(host as ExecutionContext).getContext()?.req
: host.switchToHttp().getRequest()
const baseUrl = request?.baseUrl || request?.originalUrl || request?.url || '/'
const method = isGraphQLRequest
? request?.method || 'POST'
: request?.method
const status = exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR
const path = normalizePath(
getBaseUrl(baseUrl),
[],
'#val',
)
this._counter.inc({
method,
path,
status,
})
if ( ! isGraphQLRequest) {
super.catch(exception, host)
}
}
}