是否可以从NestJs内部的类验证器返回自定义错误响应。

NestJS当前返回如下错误消息:

{
    "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"
        }
    }
}

最佳答案

如果您想装饰异常(exception)情况下的响应,Nestjs内置了名为的组件异​​常过滤器。您可以找到相关文档here

以下代码段可能有助于编写自己的过滤器。

<!-- language: lang-typescript -->
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,
      });
  }
}

关于javascript - 如何从NestJS中的类验证器返回自定义响应,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57820514/

10-12 06:02