@@ -6,7 +6,12 @@ const callsite = require('callsite');
66const glob = require ( 'glob' ) ;
77const fs = require ( 'fs' ) ;
88const debug = require ( 'debug' ) ( 'ms-validation' ) ;
9- const { ValidationError, io, NotFoundError } = require ( 'common-errors' ) ;
9+ const {
10+ io,
11+ ValidationError,
12+ NotFoundError,
13+ InvalidOperationError,
14+ } = require ( 'common-errors' ) ;
1015
1116// this is taken from ajv, but removed
1217// eslint-disable-next-line max-len
@@ -57,6 +62,16 @@ ValidationError.prototype.toJSON = function toJSON() {
5762const json = filename => path . extname ( filename ) === '.json' ;
5863const slashes = new RegExp ( path . sep , 'g' ) ;
5964
65+ function safeValidate ( validate , doc ) {
66+ try {
67+ validate ( doc ) ;
68+ } catch ( e ) {
69+ return e ;
70+ }
71+
72+ return true ;
73+ }
74+
6075/**
6176 * @namespace Validator
6277 */
@@ -207,14 +222,17 @@ class Validator {
207222 return { error : new NotFoundError ( `validator "${ schema } " not found` ) } ;
208223 }
209224
210- validate ( data ) ;
225+ const isValidationCompleted = safeValidate ( validate , data ) ;
226+ if ( isValidationCompleted !== true ) {
227+ return { error : new InvalidOperationError ( 'internal validation error' , isValidationCompleted ) , doc : data } ;
228+ }
211229
212230 if ( validate . errors ) {
213231 const readable = this . $ajv . errorsText ( validate . errors ) ;
214232
215233 let onlyAdditionalProperties = true ;
216234 const error = new ValidationError ( `${ schema } validation failed: ${ readable } ` ) ;
217- validate . errors . forEach ( ( err ) => {
235+ for ( const err of validate . errors ) {
218236 if ( err . message !== 'should NOT have additional properties' ) {
219237 onlyAdditionalProperties = false ;
220238 }
@@ -224,7 +242,7 @@ class Validator {
224242 : err . field ;
225243
226244 error . addError ( new ValidationError ( err . message , 400 , field ) ) ;
227- } ) ;
245+ }
228246
229247 error . code = onlyAdditionalProperties ? 417 : 400 ;
230248
@@ -251,7 +269,14 @@ class Validator {
251269 */
252270 validate = ( schema , data ) => {
253271 const output = this . $validate ( schema , data ) ;
254- if ( 'error' in output ) {
272+
273+ if ( hasOwnProperty . call ( output , 'error' ) === true ) {
274+ // so that it can be inspected later
275+ Object . defineProperty ( output . error , '$orig' , {
276+ value : output . doc ,
277+ } ) ;
278+
279+ // reject
255280 return Promise . reject ( output . error ) ;
256281 }
257282
0 commit comments