【发布时间】:2020-06-01 20:36:35
【问题描述】:
让我们在 NestJS 项目中拥有这个控制器:
@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;
}
当this.authService.requestPasswordReset(body); 抛出EntityNotFoundError 异常时,我想以ValidationError 格式(属性、值、约束等)抛出错误。
如何手动创建此错误?当class-validator 的 DTO 验证失败时,就会抛出这些错误。这些可以只是静态验证,而不是异步数据库验证。
所以最终的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"
}
}
]
}
我需要它有一致的错误处理:)
【问题讨论】:
-
您可以创建一个异步验证器。请参阅此处的示例:github.com/typestack/…
标签: typescript nestjs class-validator