如何 return 来自 NestJS 中 class-validator 的自定义响应
How to return a custom response from the class-validator in NestJS
是否可以 return 来自 NestJs 内部的 class-validator 的自定义错误响应。
NestJS 目前 return 有这样一条错误消息:
{
"statusCode": 400,
"error": "Bad Request",
"message": [
{
"target": {},
"property": "username",
"children": [],
"constraints": {
"maxLength": "username must be shorter than or equal to 20 characters",
"minLength": "username must be longer than or equal to 4 characters",
"isString": "username must be a string"
}
},
]
}
但是使用我的 API 的服务需要更类似于:
{
"status": 400,
"message": "Bad Request",
"success": false,
"meta": {
"details": {
"maxLength": "username must be shorter than or equal to 20 characters",
"minLength": "username must be longer than or equal to 4 characters",
"isString": "username must be a string"
}
}
}
Nestjs 有名为 Exception filters 的内置组件,如果你想在出现异常时修饰你的响应。您可以找到相关文档 here.
以下代码片段可能有助于编写您自己的过滤器。
import { ExceptionFilter, Catch, ArgumentsHost, BadRequestException } from '@nestjs/common';
import { Request, Response } from 'express';
@Catch(BadRequestException)
export class BadRequestExceptionFilter implements ExceptionFilter {
catch(exception: BadRequestException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status = exception.getStatus();
response
.status(status)
// you can manipulate the response here
.json({
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
});
}
}
是否可以 return 来自 NestJs 内部的 class-validator 的自定义错误响应。
NestJS 目前 return 有这样一条错误消息:
{
"statusCode": 400,
"error": "Bad Request",
"message": [
{
"target": {},
"property": "username",
"children": [],
"constraints": {
"maxLength": "username must be shorter than or equal to 20 characters",
"minLength": "username must be longer than or equal to 4 characters",
"isString": "username must be a string"
}
},
]
}
但是使用我的 API 的服务需要更类似于:
{
"status": 400,
"message": "Bad Request",
"success": false,
"meta": {
"details": {
"maxLength": "username must be shorter than or equal to 20 characters",
"minLength": "username must be longer than or equal to 4 characters",
"isString": "username must be a string"
}
}
}
Nestjs 有名为 Exception filters 的内置组件,如果你想在出现异常时修饰你的响应。您可以找到相关文档 here.
以下代码片段可能有助于编写您自己的过滤器。
import { ExceptionFilter, Catch, ArgumentsHost, BadRequestException } from '@nestjs/common';
import { Request, Response } from 'express';
@Catch(BadRequestException)
export class BadRequestExceptionFilter implements ExceptionFilter {
catch(exception: BadRequestException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status = exception.getStatus();
response
.status(status)
// you can manipulate the response here
.json({
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
});
}
}