poppinss / indicative

Indicative is a simple yet powerful data validator for Node.js and browsers. It makes it so simple to write async validations on nested set of data.
https://indicative.adonisjs.com/
MIT License
417 stars 52 forks source link

Promise should reject with Error object #107

Closed Andreyco closed 7 years ago

Andreyco commented 7 years ago

Current behaviour: When validation fails, Promise is rejected with array object.

Expected behaviour Instead, it should be rejected with Error object. Node happen to complain about this.

Notes Rejecting with Error object would probably cause breaking change.

thetutlage commented 7 years ago

There is a difference between an error and an exception. The error object is created when an exception is thrown and developers are tend to deal with them.

Whereas validation falls in errors category, where you need a sensible object/array with custom messages, so that you can let people understand and act upon them.

The Promise spec may says that rejection should have error object, but specs are not written keeping business logic in mind.

Andreyco commented 7 years ago

I totally agree with you... What I was talking about is something like this...

Custom validation error object

function ValidationError(errors) {
  this.name = 'ValidationError';
  this.message = 'fix you things';
  this.stack = (new Error()).stack;

  this.errors = errors;

  this.getAll = function() {
    // return all
  }

  this.getForKey = function(key) {
    // return all errors for given key
  }

  this.getFirstForKey = function(key) {
    // return first error for given key
  }
}

ValidationError.prototype = Object.create(Error.prototype);
ValidationError.prototype.constructor = ValidationError;

Validation fn

function validate(data, schema, messaged) {
  return new Promise((resolve, reject) => {
    if (fails) {
      reject(new ValidationError(errArray));
    }

    resolve(true || orWhatever)
  });
}

Handle validation

try {
  await validate(data, rules, messages);
} catch (valErr) {
  console.log(valErr.getAll());
}

Pros

Cons

thetutlage commented 7 years ago

Ideally yes, but I am planning to add support for error formats, where you can define a format in which errors should be received.

Not sure if it will be possible to always reject with an error, since it will be dependent upon the formatted your are using.

ansarizafar commented 6 years ago

I totally agree with @Andreyco. Is the suggested change merged. Can I handle validation like this now.

try {
  await validate(data, rules, messages);
} catch (valErr) {
  console.log(valErr.message);
}