首页 > 解决方案 > NestJs 验证管道不返回任何消息

问题描述

在 NestJs 中,我无法弄清楚如何从 ValidationPipe 获取验证错误消息。始终发送不包含此类“消息”参数的通用响应。:

{
  "statusCode": 400,
  "timestamp": "2021-05-22T09:59:27.708Z",
  "path": "/batchs"
}

在 main.ts 我把管道定义

  app.useGlobalPipes(new ValidationPipe());

这是我的 dto

export class BatchCreateDto {
    @ApiProperty()
    @IsNotEmpty({ message: 'username is required' })
    code: string;

    @ApiProperty({ type: Lang })
    title: Lang;

    @ApiProperty({ type: Lang })
    description: Lang;

    @ApiProperty()
    startingDate: Date;

    @ApiProperty()
    duraitonInHours: number;


}

如果我将带有 emty“代码”字段的数据发送到 api,则 api 会返回不包含消息参数的通用错误请求响应。如果“代码”字段包含任何数据,则没有问题,api 将对象插入数据库。所以我知道验证管道有效,但是如果验证失败,为什么不返回任何详细消息。我想获取包含“需要用户名”或任何通用消息之类的消息参数。感谢帮助。

更新导致错误的请求正文

{
  "code": "",
  "title": {
    "en": "this is test",
    "tr": "bu testtir"
  },
  "description": {
    "en": "some explination...",
    "tr": "bazı açıklamalar..."
  },
  "startingDate": "2021-05-24T07:51:03.197Z",
  "duraitonInHours": 14
}

BatchController 使用 BatchCreateDto

import { Body, Controller, Delete, Get, Param, Post, Put, Query, UsePipes, ValidationPipe } from '@nestjs/common';
import { BatchService } from '../services/batch.service';
import { ApiBody, ApiTags } from '@nestjs/swagger';
import { BatchCreateDto } from 'src/entities/dto/batch.create.dto';

@ApiTags('Batchs')
@Controller('batchs')
export class BatchController {
    constructor(private batchService: BatchService) { }

    @Post()
    public async addBatch(@Body() batch: BatchCreateDto) {
        const result = await this.batchService.add(batch);
        return result;
    }



}

标签: nestjsclass-validator

解决方案


推荐阅读