Permalink
Browse files

Improved error handling, so if it falls back to calling the hook as t…

…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...
1 parent 64905b2 commit 84dfa162946c512c06f9177ee1dedfc170c5260e @bnoguchi committed Jun 14, 2011
Showing with 23 additions and 5 deletions.
  1. +2 −1 hooks.js
  2. +21 −4 test.js
View
@@ -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);
};
View
25 test.js
@@ -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();
@@ -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();
@@ -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) {
@@ -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);
@@ -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());

0 comments on commit 84dfa16

Please sign in to comment.