How to throw Joi warnings instead of errors

Viewed 47

I am using Joi package for validation and as of now, whenever I pass invalid values to the payload (e.g. number instead of string), the validation rules don't allow me to ingest the event into the database.

const registerCommandSchema = baseEntitySchema.append({
  name: Joi.string().required(),
  type: Joi.string()
    .valid(...Object.values(EntityType))
    .required(),
  manualEntry: Joi.boolean().required(),
  sourceIp: Joi.string().ip().required(),
  caid: Joi.string(),
  status: Joi.string().valid(...Object.values(Status)),
  shortId: Joi.string(),
});

export class RegisterCommand extends ICommand<RegisterCommandDto> {
  schema(): Joi.ObjectSchema {
    return registerCommandSchema;
  }
}

This is the baseEntitySchema

export abstract class ICommand<Dto> {
  constructor(public readonly dto: Dto) {
  }

  /**
   * Returns the sub-class specific Joi.ObjectSchema to be used during this.validate()
   */
  abstract schema(): Joi.ObjectSchema;

  /**
   * Validate command to ensure there is no invalid field values
   * e.g. missing properties, invalid values ... etc
   * Any validation issue => throws an Error.
   */
  validate(): void {
    const { error } = this.schema().validate(this.dto);
    if (!error) {
      return;
    }
    throw new ClientError(error.details[0].message);
  }
}

And this is the handler that calls the register command:

import { IHookAction, HookAction } from '@nestpack/hooks';
import { RegisterCommand } from '../impl';
import { EntityRepository } from '../../repositories/entityRepository';

@HookAction(RegisterCommand)
export class RegisterCommandHandler implements IHookAction {
  constructor(private readonly repository: EntityRepository) {}

  async handle(command: RegisterCommand) {
    console.log('RegisterCommandHandler.execute');
    console.log(JSON.stringify(command, null, 2));

    command.validate();

    const { dto } = command;
    await this.repository.register(dto);
  }
}

Now what I would like to do, is instead of throwing an error, simply log the warning (with the content of an error) and allow the event to be put to the database. How can I do that?

I've tried replacing the throw new ClientError(error.details[0].message); with info(error.details[0].message) but it didn't work (info is similar to console.log)

0 Answers
Related