-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathexception-handler.filter.ts
More file actions
executable file
·137 lines (110 loc) · 4.47 KB
/
Copy pathexception-handler.filter.ts
File metadata and controls
executable file
·137 lines (110 loc) · 4.47 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
/**
* @see https://github.com/mikemajesty/nestjs-microservice-boilerplate-api/blob/master/guides/middlewares/exception-handler.filter.md
*/
import { ArgumentsHost, Catch, ExceptionFilter as AppExceptionFilter, HttpException } from '@nestjs/common'
import { AxiosError } from 'axios'
import { ZodError } from 'zod'
import { ILoggerAdapter } from '@/infra/logger/adapter'
import { DateUtils } from '@/utils/date'
import { ApiBadRequestException, ApiErrorType, ApiInternalServerException, BaseException } from '@/utils/exception'
import { DefaultErrorMessage } from '@/utils/http-status'
import { ObjectUtil } from '@/utils/object'
import { AnyType } from '@/utils/types'
@Catch()
export class ExceptionHandlerFilter implements AppExceptionFilter {
constructor(private readonly loggerService: ILoggerAdapter) {}
catch(exception: BaseException, host: ArgumentsHost): void {
const context = host.switchToHttp()
const response = context.getResponse()
const request = context.getRequest()
const status = this.getStatus(exception)
const requestId = (request as { id: string }).id
exception.traceid = [exception.traceid, requestId].find(Boolean) as string
response.status(status)
this.loggerService.logger(request, response)
this.logError(exception)
const message = this.getErrorMessage(exception, status)
const errorResponse: ApiErrorType = {
error: {
code: status,
traceid: exception.traceid,
context: exception.context ?? ObjectUtil.reach(exception, (o) => o.parameters.context),
details: ObjectUtil.reach(exception, (o) => o.parameters.details),
name: exception.name || ObjectUtil.reach(exception, (o) => o.constructor.name, Error.name),
message,
timestamp: DateUtils.build({ format: 'yyyy-MM-dd HH:mm:ss', type: 'iso' }),
path: request.url
}
}
response.json(errorResponse)
}
private logError(exception: BaseException): void {
this.loggerService.error(exception)
}
private getErrorMessage(exception: BaseException, status: number): string[] {
const defaultError = DefaultErrorMessage[String(status)]
if (defaultError) {
return [defaultError]
}
if (exception instanceof ZodError) {
return this.formatZodErrors(exception)
}
if (exception instanceof AxiosError) {
return this.formatAxiosError(exception)
}
return this.formatBaseException(exception)
}
private formatZodErrors(exception: ZodError): string[] {
return exception.issues.map((issue: AnyType) => {
const isUnrecognizedKeys = issue.code === 'unrecognized_keys'
const path = isUnrecognizedKeys
? (issue as ZodUnrecognizedKeysIssue).keys?.join('.')
: issue.path?.join('.') || 'key'
const arrayPositionMatch = /^\d+/.exec(path)
if (arrayPositionMatch?.[0]) {
const position = Number(arrayPositionMatch[0])
const property = path.replace(/^\d+\./, '')
return `array position: ${position}, property: ${property}: ${issue.message.toLowerCase()}`
}
return `${path}: ${issue.message}`
})
}
private formatAxiosError(exception: AxiosError): string[] {
if (ObjectUtil.reach(exception, (o) => o.response.data)) {
const responseData = ObjectUtil.reach(exception, (o) => o.response.data) as AnyType
if (typeof responseData === 'string') {
return [responseData]
}
if (responseData.message) {
return Array.isArray(responseData.message) ? responseData.message : [responseData.message]
}
}
return [exception.message || 'External API request failed']
}
private formatBaseException(exception: BaseException): string[] {
const response = exception.getResponse()
if (Array.isArray(response)) {
return response as string[]
}
if (typeof response === 'object' && response !== null && 'message' in response) {
const message = (response as { message: string | string[] }).message
return Array.isArray(message) ? message : [message]
}
return [exception.message || 'An unexpected error occurred']
}
private getStatus(exception: BaseException): number {
if (exception instanceof ZodError) {
return ApiBadRequestException.STATUS
}
if (exception instanceof HttpException) {
return exception.getStatus()
}
return exception['status'] || ApiInternalServerException.STATUS
}
}
type ZodUnrecognizedKeysIssue = {
code: 'unrecognized_keys'
keys: string[]
path: (string | number)[]
message: string
}