oferei / json-gate

A friendly, fast JSON schema validator
MIT License
100 stars 16 forks source link

When using asynchronously, `try/catch` re-calls `done()` callback #24

Closed chimmelb closed 9 years ago

chimmelb commented 10 years ago

The main validateObject(obj, schema, done) function is written as a try/catch block. When used asynchronously, any error down the callback chain (which could be MANY function calls away), is part of json-gate's done() stack, which falls inside the try/catch. Meaning that json-gate gobbles up the errors of functions down the chain (hiding the error a bit), and also calling the done callback again, messing up control flow (such as a double-send for HTTP handling).

One options would be: Let the try/catch resolve in asynchronous mode before calling done() without errors.

chimmelb commented 10 years ago

Perhaps something like this:

module.exports = function(obj, schema, done) {
  var error = null;
    try {
        validateSchema(obj, schema, []);
    } catch(err) {
      error = err;
    }
    if( done )
    {
      if( error ) done( error );
      else done( null, obj );
      //or remove the if-else: done( error, obj );
    }
    else if( error )
      throw error;
};

Technically one more if-check, and one more variable created, but that should be pretty minimal, if not compiled away.

oferei commented 10 years ago

thanks for the heads up. I'll take a closer look at it soon.

oferei commented 9 years ago

took me a while to get to it, but it's fixed. thanks again.