Search code examples
javascripttypescriptnestjsclass-validator

Respond with a custom status code in validation process


I'd like to change the status code during the validation stage.

import { IsEmail, IsNotEmpty } from 'class-validator';

export class CreateUserDto {
  @IsEmail()
  email: string;

  @IsNotEmpty()
  password: string;
}

With these rules in place, if a request hits our endpoint with an invalid email property in the request body, the application will automatically respond with a 400 Bad Request code.

My question is, is it possible to change the status code from 400 to 422 (Unprocessable Entity)?


Solution

  • You'll have to create a Filter to catch BadRequestExceptions and transform them yourself to a 422. Whether you are looking to just change the status code, or the entire error response, you should have full access to the res object and be able to change things then.