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

Viewed 2051

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'
}
1 Answers

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);
}
Related