From 5d6d5ed7c9e2c0663f3ea473c7190b579a8a6dad Mon Sep 17 00:00:00 2001 From: Eran Hammer Date: Sat, 28 Sep 2019 21:37:14 -0700 Subject: [PATCH] Fix error() function. Closes #2147 --- lib/validator.js | 4 ++++ test/base.js | 9 +++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/lib/validator.js b/lib/validator.js index 3a6e22d0a..8891b768e 100755 --- a/lib/validator.js +++ b/lib/validator.js @@ -461,6 +461,10 @@ internals.finalize = function (value, errors, helpers) { if (!Array.isArray(errors)) { errors = [errors]; } + + for (const error of errors) { + Assert(error instanceof Error || error instanceof Errors.Report, 'error() must return an Error object'); + } } else { errors = [schema._flags.error]; diff --git a/test/base.js b/test/base.js index 6f2d0ecad..d31f73b55 100755 --- a/test/base.js +++ b/test/base.js @@ -1372,7 +1372,6 @@ describe('any', () => { } }); }).to.throw('Must provide a valid Error object or a function'); - }); it('errors on missing error option', () => { @@ -1386,7 +1385,6 @@ describe('any', () => { } }); }).to.throw('Missing error'); - }); describe('with a function', () => { @@ -1540,6 +1538,13 @@ describe('any', () => { expect(result2.value).to.equal({ a: [' xx', 'yy?'], b: ' x' }); expect(result2.error).to.be.an.error('my new error message'); }); + + it('errors on invalid error function', () => { + + const schema = Joi.number().error(() => 'not an Error'); + + expect(() => schema.validate('x')).to.throw('error() must return an Error object'); + }); }); });