javascript - How to return a custom response from the class-validator in NestJS
问题描述
Is it possible to return a custom error response from class-validator inside of NestJs.
NestJS currently returns an error message like this:
{
"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"
}
},
]
}
However the service that consumes my API needs something more akin to:
{
"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 has built-in compoments named Exception filters, if you want to decorate your response in case of exceptions. You can find the relevant documentations here.
The following snippet could be helpful for writing your own filter.
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,
});
}
}
推荐阅读
- html - 滚动时不考虑阴影
- c# - 将文件从 WinForms 上传到 .Net Core 3.1 API
- jupyter-notebook - 更改 Jupyter 笔记本中的文本光标颜色
- jquery - 如何在 jquery 中使用非选择器 - 不工作
- swift - 为两个单独的 SKSpriteNodes 同时随机运行两个 SKAction
- r - st_write 拒绝覆盖 R 中 geopackage 中的图层
- xml - 不断收到“没有元素声明”错误。这个 XML/DTD 有什么问题?
- r - R 库文件夹位置和 Docker
- c++ - LLVM如何检测和忽略库(内置)函数?
- javascript - 模板文字中的多重评估...如何改进样式组件的填充计算?