diff --git a/index.js b/index.js index 0a99d98..f24cd12 100644 --- a/index.js +++ b/index.js @@ -47,18 +47,23 @@ module.exports = function wrapError(message, rules, options = {}) { if (!preserveOriginalErrors) { return [ new ValidationError(message) ]; } else { - let newRootErrors = (hasRootValidationErrors) - ? errorsByType.validationRoot.map((error) => { - // TODO: Currently we cannot set `originalError` due to a bug in `create-error`; switch to a better error implementation - // return new ValidationError(`${message} (${error.message})`, { originalError: error }) - return new ValidationError(`${message} (${error.message})`) - }) - : [ new ValidationError(message) ]; - - return concat([ - newRootErrors, - errorsByType.validationPath - ]); + // If possible, we try to move any subpath errors into the subErrors of an (optionally newly-created) root error. Otherwise, it can become difficult for the user to correlate together the root and subpath errors that are related, when we start changing the messages of the root errors. + if (errorsByType.validationRoot.length === 0) { + return [ new ValidationError(message, { subErrors: errorsByType.validationPath }) ]; + } else if (errorsByType.validationRoot.length === 1) { + let error = errorsByType.validationRoot[0]; + + // TODO: Currently we cannot set `originalError` due to a bug in `create-error`; switch to a better error implementation + return [ new ValidationError(`${message} (${error.message})`, { subErrors: errorsByType.validationPath }) ]; + } else { + // If there are multiple root errors, we cannot determine which root error the subpath errors belong to, so we'll just provide them as a flat list + return concat([ + errorsByType.validationRoot.map((error) => { + return new ValidationError(`${message} (${error.message})`) + }), + errorsByType.validationPath + ]); + } } } else { return [];