Closed Andreyco closed 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.
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
getAll
, getAllFor
, getFirstFor
, ... without bloating validator itself (yep, could be added via helper functions)Cons
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.
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);
}
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.