我怎么能包装每一个快递路线处理程序与另一个function
基本上我想代替这个…
app.get(routes.test, function(req, res, next){ actualRouteHandler(req, res, next) // Always returns a promise or throws. .catch(function(err) { next(err); }); });
有这个: app.get(routes.test, catchWrap(actualRouteHandler));
或者类似的东西,我试着弄乱fn.apply和东西,但我找不到一个方法来传递actualRouteHandler正确的参数(请求,水库,下一个),仍然有function。 我是否需要返回一个函数或类似的东西?
编辑:我认为可能有这样做的库,但我们没有访问这一点代码中的实际expression应用程序。
在你的具体情况下, catchWrap
看起来像这样:
function catchWrap(originalFunction) { return function(req, res, next) { try { return originalFunction.call(this, req, res, next); } catch (e) { next(e); } }; }
这将返回一个新的函数,当被调用的时候,会用你的catch包装器调用原来的函数。 关键部分是它创build并返回一个函数( return function(req, res, next) { ... };
)和这一行:
return originalFunction.call(this, req, res, next);
Function#call
调用给定的函数,说明在调用期间使用什么(在上面我们传递我们收到的this
)以及在调用中使用的参数。
你会使用它,如你所示:
app.get(routes.test, catchWrap(actualRouteHandler));
或者,如果您更愿意将实际处理程序定义为匿名函数:
app.get(routes.test, catchWrap(function(req, res, next) { // ...handler code here... }));
这catchWrap
是特定于你的情况,因为你想调用next(e)
与例外抛出。 “在另一个函数中包装这个函数”的通用forms是这样的:
function catchWrap(originalFunction) { return function() { try { // You can do stuff here before calling the original... // Now we call the original: var retVal = originalFunction.apply(this, arguments); // You can do stuff here after calling the original... // And we're done return retVal; } catch (e) { // you can do something here if you like, then: throw e; // Or, of course, handle it } }; }
arguments
是由JavaScript提供的伪数组,其中包含当前函数被调用的所有参数。 Function#apply
#apply就像Function#call
,除了给参数使用一个数组(或伪数组)而不是离散的。
以下简单的方法可以用来设置一个通用的error handling程序 –
步骤1:在注册路由之后编写error handling程序。 所以,例如,如果你正在注册你的多个路线,像这样:
config.getGlobbedFiles('./app/routes/modules/**/*.js').forEach(function (routePath) { require(path.resolve(routePath))(app); });
注册路由后,你可以设置一个通用的error handling程序 –
app.use(function (err, req, res, next) { // If the error object doesn't exists if (err != undefined) { //do error handling } else { //no error found } });
步骤2:在路由处理程序中,如果没有发现错误,则需要确保调用“next()”。 如果发生错误,您需要调用“next(err)”。