Print class-validator validation errors in NestJS

A simple way to print any and all errors in Nest.js, for people who aren't experienced with it.

Print class-validator validation errors in NestJS
Photo by Lennert Naessens / Unsplash

Facing some strange validation error  I had a hard time understanding, I grew frustrated from not being able to print the actual error, instead only getting a 400: Bad Request error in the frontend's console.

Since the validation occured before any of the controller's code, and I am totally inexperienced with NestJS (and some of VS Code's debugging features), I felt helpless as I stood by and watched my code fail, unable to figure out precisely what was going wrong.

It turns out, you can easily add a pipe to your Nest.js app, one that will intercept all undhandled errors, and allow you to deal with them, no matter where in your code they originated from.

I wouldn't call it a perfect solution. Some neat breakpoints and a better understanding and usage of your favorite IDE's debugger is most likely a better choice, but it helped me, some maybe it will help you, if you find yourself in a similar pinch.

Here it is:

  app.useGlobalPipes(
    new ValidationPipe({
      exceptionFactory: (validationErrors: ValidationError[] = []) => {
        console.error(JSON.stringify(validationErrors));
        return new BadRequestException(validationErrors);
      },
      transform: true,
    }),
  );

Simple, short, easy to add and to clean up afterwards.