Permalink
Browse files

Better fallbacks for the default error callback, when lazily setting …

…up hooks.
  • Loading branch information...
1 parent 6c2f7c9 commit c5790303b7d2588bf531a8c671dc728046566a60 @bnoguchi committed May 22, 2011
Showing with 27 additions and 14 deletions.
  1. +14 −14 hooks.js
  2. +13 −0 test.js
View
28 hooks.js
@@ -37,8 +37,6 @@ module.exports = {
return;
}
- if (!errorCb) errorCb = fn;
-
var proto = this.prototype || this
, pres = proto._pres = proto._pres || {}
, posts = proto._posts = proto._posts || {};
@@ -48,14 +46,16 @@ module.exports = {
proto[name] = function () {
var self = this
, hookArgs // arguments eventually passed to the hook - are mutable
+ , lastArg = arguments[arguments.length-1]
, pres = this._pres[name]
, posts = this._posts[name]
, _total = pres.length
, _current = -1
, _asyncsLeft = proto[name].numAsyncPres
, _next = function () {
- if (arguments[0] instanceof Error)
- return errorCb(arguments[0]);
+ if (arguments[0] instanceof Error) {
+ return handleError(arguments[0]);
+ }
var _args = Array.prototype.slice.call(arguments)
, currPre
, preArgs;
@@ -82,8 +82,9 @@ module.exports = {
total_ = posts.length;
current_ = -1;
next_ = function () {
- if (arguments[0] instanceof Error)
- return errorCb(arguments[0]);
+ if (arguments[0] instanceof Error) {
+ return handleError(arguments[0]);
+ }
var args_ = Array.prototype.slice.call(arguments, 1)
, currPost
, postArgs;
@@ -105,6 +106,12 @@ module.exports = {
--_asyncsLeft || _done.apply(self, hookArgs);
}
}
+ function handleError (err) {
+ if (errorCb) return errorCb(err);
+ if ('function' == typeof lastArg)
+ return lastArg(err);
+ return fn(err);
+ }
return _next.apply(this, arguments);
};
@@ -150,14 +157,7 @@ module.exports = {
},
_lazySetupHooks: function (proto, methodName) {
if ('undefined' === typeof proto[methodName].numAsyncPres) {
- if (!proto[methodName].error) {
- proto[methodName].error = function error (err) {
- var lastArg = args[args.length-1];
- if (typeof lastArg == 'function')
- lastArg.call(proto, err);
- };
- }
- this.hook(methodName, proto[methodName], proto[methodName].error);
+ this.hook(methodName, proto[methodName]);
}
}
};
View
13 test.js
@@ -480,5 +480,18 @@ module.exports = {
var a = new A();
a.save();
a.value.should.equal(2);
+ },
+
+ "a lazy hooks setup should handle errors via a method's last argument, if it's a callback": function () {
+ var A = function () {};
+ _.extend(A, hooks);
+ A.prototype.save = function (fn) {};
+ A.pre('save', function (next) {
+ next(new Error("hi there"));
+ });
+ var a = new A();
+ a.save( function (err) {
+ err.should.be.an.instanceof(Error);
+ });
}
};

0 comments on commit c579030

Please sign in to comment.