Custom error formatter in default ValidationPipe in Nestjs

In the main.ts

import { formatErrors } from './common/validators/custom-validations';
...
...
...
 app.useGlobalPipes(
    new ValidationPipe({
      exceptionFactory: formatErrors,
    }),
  );

In common/validators/custom-validations.ts

import { BadRequestException, HttpStatus } from '@nestjs/common';

export function formatErrors(errors) {
  const errs = {};
  let upErrors = {};
  errors.forEach((err) => {
    errs[err.property] = errs[err.property] || [];
    const messages = [];
    for (let key in err.constraints) {
      messages.push(err.constraints[key]);
    }
    errs[err.property] = messages;
    upErrors = {
      errors: errs,
      statusCode: HttpStatus.BAD_REQUEST,
    };
  });
  return new BadRequestException(upErrors);
}

Output response on input validation of DTO:

{
    "errors": {
        "first_name": [
            "first_name should not be empty"
        ],
        "email": [
            "email must be an email",
            "email should not be empty"
        ]
    },
    "statusCode": 400
}

Leave a Reply

Your email address will not be published. Required fields are marked *