Closed fider closed 5 years ago
Hi @fider,
Can you show what your model looks like with your CustomError decorator on it please?
export function CustomError(err: Error | ValidationErrorFunction, options?: ErrorOptions) : PropertyDecorator {
return constraintDecorator([], (schema : Schema) => {
return schema.error(err, options);
});
}
export class MyError extends Error {}
Case 1 - @CustomError
first (received ValidationError instead of my custom error)
export class DataToValidate {
@CustomError( new MyError('XXX') ) // ! CustomError is first
@StringSchema()
public p1: string;
}
let result = (new Validator).validate({p1: 1});
console.log(result.error); // ValidationError: "p1" is not allowed but I expected MyError('XXX')
Case 2 - @CustomError
not first (runtime error)
export class DataToValidate {
@StringSchema()
@CustomError( new MyError('XXX') ) // ! CustomError is NOT firs decorator
public p1: string;
}
// Evaluation causes:
// ConstraintDefinitionError: A validation schema already exists for property: p1
Thank you for raising this issue! 🙂
Decorators are applied in reverse order. The following are roughly requivalent:
@Third
@Second
@First
foo = 123;
bar = Third(Second(First(123)));
Case 2 will error because tsdv-joi infers the base schema to use by "magic" (inspected the generated type metadata). In this case, when you apply @CustomError()
, tsdv-joi sees there's no existing schema, and guesses that it should use the string schema. However, because you've also specifically applied a base schema decorator, it's going to try setting a base schema on a property that already has one. Hence, the ConstraintDefinitionError.
Case 1 does not work how you expect, because you have not told the validator what schema class to use. When validating plain objects, you must also pass the schema class. Here is a working example:
export class DataToValidate {
@CustomError(new MyError('XXX'))
public p1: string;
}
let result = new Validator().validate({ p1: 1 }, DataToValidate);
console.log(result.error);
I have added the missing Error
decorator based on your example, thank you! This will be in the next release of tsdv-joi. (Be aware, because tsdv-joi is based on an old version of Joi, it does not supported passing the extra options
argument to error()
.)
This has been fixed in v.0.0.13
Decorator for custom error definition is not exposed (any.error).
I tried to expose it:
but it fails.
Error 1) I am receiveing Joi error instead of my custom error. Error 2) If it is not first decorator of property then I have runtime error
ConstraintDefinitionError: A validation schema already exists for property:
Any ideas how to fix it (add custom error decorator)?