1 year ago

#340773

test-img

Miad Abdi

How to return an object as error message from DTO in nestjs?

How can I return an object as validation error instead of strings?

We have our own error structure and I could do what I want, using JSON.stringify and JSON.parse, like follows:

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(() => Date)
  @Transform(val => new Date(val))
  datInputCttps: Date;
}

And then in main.ts when initializing the app I use a custom exceptionFactory:


  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      whitelist: true,
      exceptionFactory: function(validationErrors: ValidationError[]) {
        const modifiedError = [];

        validationErrors.forEach(error => {
          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 === "object",
              // so we must check for that, too. Thankfully, null is falsey, so this suffices:
              if (!parsed && 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);
      },
    }),
  );

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.

Therefore I am looking for a way to not use JSON and return object as an error message.

class-transformer v0.2.3

class-validator v0.10.0

we have no problem updating packages, if that makes any difference. Thanks.

node.js

nestjs

dto

class-validator

class-transformer

0 Answers

Your Answer

Accepted video resources