Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize error message in Nest js using class-validator

I am working on a nest project, and using class-validator for validation.

Currently if there is any validation error, I am getting error response as

{
    "statusCode": 400,
    "message": [
        "Title is too long. Maximal length is 50 characters, but actual is $value",
        "Title is too short. Minimal length is 10 characters, but actual is $value"
    ],
    "error": "Bad Request"
}

But instead of message as array of string, can we have message as array of object. So, that FE can easy figure out which field is having the error, like

{
    "message": [
        { "field": "title", "error": "Title is too long. Maximal length is 50 characters, but actual is $value" },
        { "field": "title", "error": "Title is too short. Minimal length is 10 characters, but actual is $value" }
    ]
}
like image 808
Shivansh Kumar Avatar asked Jul 11 '26 01:07

Shivansh Kumar


1 Answers

You can use exception filters in NestJS to handle or add custom user-friendly responses.

However, for the class-validator, there is the same mechanism by using exceptionFactory() in your validationPipe to modify the error returned by the class-validator, here is an example code for it:

app.useGlobalPipes(
  new ValidationPipe({
    exceptionFactory: (validationErrors: ValidationError[] = []) => {
      return new BadRequestException(
        validationErrors.map((error) => ({
          field: error.property,
          error: Object.values(error.constraints).join(', '),
        })),
      );
    },
  }),
);

Hope it will works for you!

like image 166
Yazan Zoghbi Avatar answered Jul 13 '26 20:07

Yazan Zoghbi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!