让我们在 NestJS 项目中使用这个 Controller :
@Post('resetpassword')
@HttpCode(200)
async requestPasswordReset(
@Body() body: RequestPasswordResetDTO,
): Promise<boolean> {
try {
return await this.authService.requestPasswordReset(body);
} catch (e) {
if (e instanceof EntityNotFoundError) {
// Throw same exception format as class-validator throwing (ValidationError)
} else throw e;
}
}
Dto定义:
export class RequestPasswordResetDTO {
@IsNotEmpty()
@IsEmail()
public email!: string;
}
我想在
ValidationError
中抛出错误this.authService.requestPasswordReset(body);
时的格式(属性、值、约束等)抛出一个 EntityNotFoundError
异常(exception)。如何手动创建此错误?当 DTO 验证通过
class-validator
时,这些错误才会被抛出失败。这些可以只是静态验证,而不是异步数据库验证。所以最终的 API 响应格式应该是例如:
{
"statusCode": 400,
"error": "Bad Request",
"message": [
{
"target": {
"email": "not@existing.email"
},
"value": "not@existing.email",
"property": "email",
"children": [],
"constraints": {
"exists": "email address does not exists"
}
}
]
}
我需要它有一致的错误处理:)
最佳答案
添加 ValidationPipe
时到您的应用程序,提供自定义 exceptionFactory
:
app.useGlobalPipes(
new ValidationPipe({
exceptionFactory: (validationErrors: ValidationError[] = []) => {
return new BadRequestException(validationErrors);
},
})
);
这应该是您获得预期结果所需的全部内容。
为了比较,你可以查看原始的 NestJS 版本 here .
关于typescript - 在 NestJS 中抛出与 `class-validator` 相同的错误格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60270468/