让我们在 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;
}
我想在抛出异常时抛出ValidationError
格式错误(属性、值、约束等)。this.authService.requestPasswordReset(body);
EntityNotFoundError
如何手动创建此错误?这些错误只是在 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"
}
}
]
}
我需要它有一致的错误处理:)