Javascript 如何在nestjs中使用globalPipse进行自定义响应
我使用“类验证器”的dto在user.controller中编写了一个apiJavascript 如何在nestjs中使用globalPipse进行自定义响应,javascript,node.js,typescript,nestjs,Javascript,Node.js,Typescript,Nestjs,我使用“类验证器”的dto在user.controller中编写了一个api @Post('/') public async createUser( @Res() res, @Body() createUserDto: CreateUserDto, ) { ... do something } 我在main.ts里放上了通用的全球管道 app.useGlobalPipes( new ValidationPipe({ whiteli
@Post('/')
public async createUser(
@Res() res,
@Body() createUserDto: CreateUserDto,
) {
... do something
}
我在main.ts里放上了通用的全球管道
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
transform: true,
forbidNonWhitelisted: true,
transformOptions: {
enableImplicitConversion: true,
},
}),
);
当我请求api时,我得到下面的响应
{
"statusCode": 400,
"message": [
"userName should not be empty",
"userName must be a string",
],
"error": "Bad Request"
}
到目前为止,它在nestjs中工作没有问题。但我想得到这样的自定义响应
{
"code": 400,
"errorReason": [
"userName should not be empty",
"userName must be a string",
],
"msg": "Bad Request",
"success": false
}
我可以通过维护上述代码获得此自定义响应吗?如果它能做到这一点,你能给我一些建议或一些代码吗?
感谢您阅读我的问题。在Nest中,管道有助于验证、转换传入对象、在某些情况下可能与数据库通信,以及在出现任何错误时抛出错误。如果要在抛出错误后更改响应,则需要研究使用
@Catch()
导出类CatchAllFilter实现ExceptionFilter{
捕获(异常:错误,主机:ArgumentHost){
物件
.status((exception.getStatus&&exception.getStatus())| 500)
.发送({
(exception.getResponse&…exception.getResponse())| |…{message:exception.message},
成功:错
});
}
}
上面的代码肯定会导致类型错误,但它会引导您走上正确的道路