Created
May 29, 2019 02:41
-
-
Save syrxw/5fbf33b01fba705c3e563c0b707b321d to your computer and use it in GitHub Desktop.
next.js 使用validatePipe的错误过滤器,自定义错误信息返回
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
BadRequestException, | |
ExceptionFilter, | |
Catch, | |
ArgumentsHost, | |
} from '@nestjs/common'; | |
import { jsonMsg } from '../common/utils/jsonMsg'; | |
import { ApiCode } from '../common/enums/api-code.enum'; | |
@Catch(BadRequestException) | |
export class ValidationExceptionFilter | |
implements ExceptionFilter<BadRequestException> { | |
public catch(exception, host: ArgumentsHost) { | |
const ctx = host.switchToHttp(); | |
const response = ctx.getResponse(); | |
const { constraints } = exception.message.message.shift(); | |
const errMsg = []; | |
for (const key in constraints) { | |
if (constraints.hasOwnProperty(key)) { | |
errMsg.push(constraints[key]); | |
} | |
} | |
response.json(jsonMsg(ApiCode.FAILED, errMsg.join(), [])); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment