Skip to content

Commit

Permalink
Improved error handling, so if it falls back to calling the hook as t…
Browse files Browse the repository at this point in the history
…he error handler, it does so with the object's scope. Throws an error if we reach that fallback check, and the hook's arity is 0.
  • Loading branch information
bnoguchi committed Jun 14, 2011
1 parent 64905b2 commit 84dfa16
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
3 changes: 2 additions & 1 deletion hooks.js
Expand Up @@ -91,7 +91,8 @@ module.exports = {
if (errorCb) return errorCb(err);
if ('function' == typeof lastArg)
return lastArg(err);
return fn(err);
if (fn.length > 0) return fn.call(self, err);
throw err;
}
return _next.apply(this, arguments);
};
Expand Down
25 changes: 21 additions & 4 deletions test.js
Expand Up @@ -134,7 +134,7 @@ module.exports = {
_.extend(A, hooks);
A.hook('save', function () {
this.value = 1;
});
}, function (err) {});
A.pre('save', function (next) {
this.v1 = 1;
next();
Expand Down Expand Up @@ -176,7 +176,7 @@ module.exports = {
_.extend(A, hooks);
A.hook('save', function () {
this.value = 1;
});
}, function (err) {});
A.post('save', function (next) {
this.value = 2;
next();
Expand Down Expand Up @@ -213,7 +213,7 @@ module.exports = {
_.extend(A, hooks);
var counter = 0;
A.hook('save', function (err) {
if (err instanceof Error) counter++;
if (err instanceof Error) return counter++;
this.value = 1;
});
A.pre('save', true, function (next, done) {
Expand All @@ -224,6 +224,23 @@ module.exports = {
counter.should.equal(1);
assert.equal(typeof a.value, 'undefined');
},
'should have access to the object scope when falling back last to the hook method as the error handler': function () {
var A = function () {
this.counter = 0;
};
_.extend(A, hooks);
A.hook('save', function (err) {
if (err instanceof Error) return this.counter++;
this.value = 1;
});
A.pre('save', true, function (next, done) {
next(new Error());
});
var a = new A();
a.save();
a.counter.should.equal(1);
assert.equal(typeof a.value, 'undefined');
},
"should proceed without mutating arguments if `next(null)` is called in a serial pre, and the last argument of the target method is a callback with node-like signature function (err, obj) {...} or function (err) {...}": function () {
var A = function () {};
_.extend(A, hooks);
Expand Down Expand Up @@ -261,7 +278,7 @@ module.exports = {
_.extend(A, hooks);
A.hook('save', function () {
this.value = 2;
});
}, function (err) {});
A.pre('save', function (next) {
this.value = 1;
next(new Error());
Expand Down

0 comments on commit 84dfa16

Please sign in to comment.