Search code examples
javascriptnode.jsnestjsclass-validator

How to get the exception error as Object in Nestjs Validation?


By default, when validation fails the response came out like

{
    statusCode: 400,
    message: [ 'Provide a url.', 'test must be a string' ],
    error: 'Bad Request'
}

How can I get the value of messages as:

{
    statusCode: 400,
    message: {
        "url": 'Provide a url.',
        "test": 'test must be a string'
    },
    error: 'Bad Request'
}

Solution

  • With the ValidationPipe you can pass an exceptionFacotry property to the options and format your errors as you want. Something like this would probably get you on the right path

    exceptionFactory: (errors) => {
      const errorMessages = {};
      errors.forEach(error => {
        errorMessages[error.property]= Object.values(error.contraints).join('. ').trim();
      });
      return new BadRequestException(errorMessages);
    }