title: How to return an object as error message from DTO in nestjs?
body: <p>How can I return an object as validation error instead of strings?</p>
  <p>We have our own error structure and I could do what I want, using <code>JSON.stringify</code> and <code>JSON.parse</code>, like follows:</p>
  <pre><code>import { IsNotEmpty, IsString, Length, IsDate } from 'class-validator';
  import { Transform, Type } from 'class-transformer';
  import {
    ErrorType,
  } from '../../../../utils/create-error-object.util';
  
  export class CreateContractTypesDto {
    @IsString()
    @IsNotEmpty()
    @Length(1, 20)
    namTitleCttps: string;
  
    @IsNotEmpty({
      message: JSON.stringify(
        ErrorType.INVALID,
        [['datInputCttps', 'label']],
      ),
    })
    @IsDate({
      message: JSON.stringify(
        ErrorType.INVALID,
        [['datInputCttps', 'label']],
      ),
    })
    // @Type(() =&gt; Date)
    @Transform(val =&gt; new Date(val))
    datInputCttps: Date;
  }
  
  </code></pre>
  <p>And then in <code>main.ts</code> when initializing the app I use a custom exceptionFactory:</p>
  <pre><code>
    app.useGlobalPipes(
      new ValidationPipe({
        transform: true,
        whitelist: true,
        exceptionFactory: function(validationErrors: ValidationError[]) {
          const modifiedError = [];
  
          validationErrors.forEach(error =&gt; {
            for (const message of Object.values(error.constraints)) {
              let errorObj;
              try {
                var parsed = JSON.parse(message);
  
                // source: https://stackoverflow.com/a/20392392/11672221
                // Handle non-exception-throwing cases:
                // Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking,
                // but... JSON.parse(null) returns null, and typeof null === &quot;object&quot;,
                // so we must check for that, too. Thankfully, null is falsey, so this suffices:
                if (!parsed &amp;&amp; typeof parsed !== 'object') {
                  throw new Error('still not an object');
                }
  
                errorObj = parsed;
              } catch (e) {
                errorObj = {
                  message,
                  parameters: error.property,
                };
              }
  
              modifiedError.push(errorObj);
            }
          });
  
          return new BadRequestException(modifiedError);
        },
      }),
    );
  </code></pre>
  <p>beside that this way I only return BadRequestException cause I couldn't get status code, I am not happy with this approach cause JSON operations are cpu intensive and ran in the main thread.</p>
  <p>Therefore I am looking for a way to not use JSON and return object as an error message.</p>
  <p>class-transformer v0.2.3</p>
  <p>class-validator v0.10.0</p>
  <p>we have no problem updating packages, if that makes any difference.
  Thanks.</p>