From 34a8b4f6bd19b009bbc673bcde09c2dbb7003f5b Mon Sep 17 00:00:00 2001 From: Sven Slootweg Date: Fri, 3 Jul 2020 13:20:21 +0200 Subject: [PATCH] Immediately fail completely when a non-validation error is encountered --- index.js | 18 +++++++++++++----- package.json | 1 + 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/index.js b/index.js index 6164202..3588cff 100644 --- a/index.js +++ b/index.js @@ -7,6 +7,7 @@ const flatten = require("flatten"); const ValidationError = require("@validatem/error"); const combinator = require("@validatem/combinator"); const validationResult = require("@validatem/validation-result"); +const matchValidationError = require("@validatem/match-validation-error"); const areErrorsFromSameOrigin = require("./src/are-errors-from-same-origin"); @@ -61,13 +62,20 @@ module.exports = function (alternatives) { for (let alternative of alternatives) { let { errors, newValue } = applyValidators(value, alternative); + + let unexpectedErrors = errors.filter((error) => !matchValidationError(error)); - if (errors.length === 0) { - return newValue; - } else if (errors.length === 1) { - allErrors.push(errors[0]); + if (unexpectedErrors.length > 0) { + // We want to immediately stop trying alternatives when a non-ValidationError occurred, since that means that something broke internally somewhere, and it is not safe to continue executing. + throw unexpectedErrors[0]; } else { - allErrors.push(errorAllOf(errors)); + if (errors.length === 0) { + return newValue; + } else if (errors.length === 1) { + allErrors.push(errors[0]); + } else { + allErrors.push(errorAllOf(errors)); + } } } diff --git a/package.json b/package.json index f55bcc5..2989ab6 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,7 @@ "dependencies": { "@validatem/combinator": "^0.1.1", "@validatem/error": "^1.0.0", + "@validatem/match-validation-error": "^0.1.0", "@validatem/validation-result": "^0.1.2", "flatten": "^1.0.3" }