Let's have this controller in NestJS project:
@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 definition:
export class RequestPasswordResetDTO {
@IsNotEmpty()
@IsEmail()
public email!: string;
}
I want to throw error in ValidationError
format (property, value, constraints, etc) when this.authService.requestPasswordReset(body);
throws an EntityNotFoundError
exception.
How I can create this error manually? Those errors are just thrown when DTO validation by class-validator
fails. And those can be just static validations, not async database validations.
So the final API response format should be for example:
{
"statusCode": 400,
"error": "Bad Request",
"message": [
{
"target": {
"email": "[email protected]"
},
"value": "[email protected]",
"property": "email",
"children": [],
"constraints": {
"exists": "email address does not exists"
}
}
]
}
I need it to have consistent error handling :)