Skip to content

Instantly share code, notes, and snippets.

@syrxw
Created May 29, 2019 02:41
Show Gist options
  • Save syrxw/5fbf33b01fba705c3e563c0b707b321d to your computer and use it in GitHub Desktop.
Save syrxw/5fbf33b01fba705c3e563c0b707b321d to your computer and use it in GitHub Desktop.
next.js 使用validatePipe的错误过滤器,自定义错误信息返回
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