-
-
Notifications
You must be signed in to change notification settings - Fork 305
/
Copy patherror.filter.ts
executable file
·42 lines (37 loc) · 1.69 KB
/
error.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
/**
* @file HttpException filter
* @module filter/error
* @author Surmon <https://github.com/surmon-china>
*/
import _isString from 'lodash/isString'
import { ExceptionFilter, Catch, HttpException, ArgumentsHost, HttpStatus } from '@nestjs/common'
import { ResponseStatus, HttpResponseError, ExceptionInfo } from '@app/interfaces/response.interface'
import { UNDEFINED } from '@app/constants/value.constant'
import { isDevEnv } from '@app/app.environment'
/**
* @class HttpExceptionFilter
* @classdesc catch globally exceptions & formatting error message to <HttpErrorResponse>
*/
@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const request = host.switchToHttp().getRequest()
const response = host.switchToHttp().getResponse()
const exceptionStatus = exception.getStatus() || HttpStatus.INTERNAL_SERVER_ERROR
const errorResponse: ExceptionInfo = exception.getResponse() as ExceptionInfo
const errorMessage = _isString(errorResponse) ? errorResponse : errorResponse.message
const errorInfo = _isString(errorResponse) ? null : errorResponse.error
const data: HttpResponseError = {
status: ResponseStatus.Error,
message: errorMessage,
error: errorInfo?.message || (_isString(errorInfo) ? errorInfo : JSON.stringify(errorInfo)),
debug: isDevEnv ? errorInfo?.stack || exception.stack : UNDEFINED
}
// default 404
if (exceptionStatus === HttpStatus.NOT_FOUND) {
data.error = data.error || `Not found`
data.message = data.message || `Invalid API: ${request.method} > ${request.url}`
}
return response.status(errorInfo?.status || exceptionStatus).jsonp(data)
}
}