如何在 post 请求中自定义错误消息?
how to customise error message in post request?
我正在使用 nest js 制作 Restfull Api
。我还使用 class-validator ,and class-transform
来验证我对 DTO
的请求。当前显示此错误
{"statusCode":400,"message":["username should not be empty","description should not be empty"],"error":"Bad Request"}
我想像这样自定义此回复
{"statusCode":400,"message":["username is required","description is required"],"error":"Bad Request from user"}
nestjs
有可能吗??
这是我的代码
https://codesandbox.io/s/nest-9ziyr?file=/src/dto/user.dto.ts
我就是这样用的
import { IsNotEmpty } from 'class-validator';
export class UserDto {
@IsNotEmpty()
username: string;
@IsNotEmpty()
description: string;
}
在控制器中
@Post('/create')
@UsePipes(ValidationPipe)
createUser(@Body() createTaskDto: UserDto): string {
console.log('====');
return 'jjjj';
}
这是我的代码
https://codesandbox.io/s/nest-9ziyr?file=/src/dto/user.dto.ts
像那样使用API
POST
https://9ziyr-5000.sse.codesandbox.io/create
使用 class-validator 您可以将消息 属性 传递给验证装饰器并更改错误消息。像这样:
import { IsNotEmpty } from 'class-validator';
export class UserDto {
@IsNotEmpty({ message: 'username is required' })
username: string;
@IsNotEmpty({ message: 'description is required' })
description: string;
}
我正在使用 nest js 制作 Restfull Api
。我还使用 class-validator ,and class-transform
来验证我对 DTO
的请求。当前显示此错误
{"statusCode":400,"message":["username should not be empty","description should not be empty"],"error":"Bad Request"}
我想像这样自定义此回复
{"statusCode":400,"message":["username is required","description is required"],"error":"Bad Request from user"}
nestjs
有可能吗??
这是我的代码 https://codesandbox.io/s/nest-9ziyr?file=/src/dto/user.dto.ts
我就是这样用的
import { IsNotEmpty } from 'class-validator';
export class UserDto {
@IsNotEmpty()
username: string;
@IsNotEmpty()
description: string;
}
在控制器中
@Post('/create')
@UsePipes(ValidationPipe)
createUser(@Body() createTaskDto: UserDto): string {
console.log('====');
return 'jjjj';
}
这是我的代码 https://codesandbox.io/s/nest-9ziyr?file=/src/dto/user.dto.ts
像那样使用API POST
https://9ziyr-5000.sse.codesandbox.io/create
使用 class-validator 您可以将消息 属性 传递给验证装饰器并更改错误消息。像这样:
import { IsNotEmpty } from 'class-validator';
export class UserDto {
@IsNotEmpty({ message: 'username is required' })
username: string;
@IsNotEmpty({ message: 'description is required' })
description: string;
}