我使用'class-validator'的dto在user.controller中编写了一个api。
@Post('/')
public async createUser(
@Res() res,
@Body() createUserDto: CreateUserDto,
) {
... do something
}
我将useGlobalPipes放在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中,管道可用于验证,转换传入的对象,在某些情况下可能与数据库进行对话以及在出现任何问题时引发错误。如果您想更改响应,则在抛出错误后,您需要研究使用“可以ExceptionFilter
在其中执行以下操作”
@Catch()
export class CatchAllFilter implements ExceptionFilter {
catch(exception: Error, host: ArgumentHost) {
res
.status((exception.getStatus && exception.getStatus()) || 500)
.send({
(exception.getResponse && ...exception.getResponse()) || ...{ message: exception.message },
success: false
});
}
}
上面的代码一定会导致类型错误,但是它应该引导您走上正确的路
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句