Skip to content

Commit d77b859

Browse files
http exception filter created
1 parent 3a07998 commit d77b859

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import {
2+
ExceptionFilter,
3+
Catch,
4+
ArgumentsHost,
5+
HttpException,
6+
HttpStatus,
7+
} from '@nestjs/common';
8+
import { I18nContext } from 'nestjs-i18n';
9+
10+
@Catch()
11+
export class HttpExceptionFilter implements ExceptionFilter {
12+
catch(exception: any, host: ArgumentsHost) {
13+
const ctx = host.switchToHttp();
14+
const response = ctx.getResponse();
15+
const request = ctx.getRequest();
16+
17+
const i18n = I18nContext.current();
18+
let status = HttpStatus.INTERNAL_SERVER_ERROR;
19+
let key = 'errors.INTERNAL_SERVER_ERROR';
20+
21+
if (exception instanceof HttpException) {
22+
status = exception.getStatus();
23+
const res = exception.getResponse() as any;
24+
25+
if (typeof res === 'string') {
26+
key = res;
27+
} else if (typeof res?.message === 'string') {
28+
key = res.message;
29+
}
30+
}
31+
32+
const translated = i18n?.t(key) ?? key;
33+
34+
response.status(status).json({
35+
statusCode: status,
36+
timestamp: new Date().toISOString(),
37+
path: request.url,
38+
message: translated,
39+
});
40+
}
41+
}

0 commit comments

Comments
 (0)