如何用另一个函数包装每个快速路由处理程序

Mar*_*mid 2 javascript function apply node.js express

基本上我想要而不是这个......

app.get(routes.test, function(req, res, next){
  actualRouteHandler(req, res, next) // Always returns a promise or throws.
    .catch(function(err) {
      next(err);
    });
});
Run Code Online (Sandbox Code Playgroud)

拥有这个: app.get(routes.test, catchWrap(actualRouteHandler));

或类似的东西,我已经尝试搞乱fn.apply和东西,但我找不到一种方法来传递actualRouteHandler正确的参数(req,res,next),仍然有功能.我需要返回一个函数或类似的东西吗?

编辑:我认为可能有库这样做但我们无法访问这段代码中的实际快速应用程序.

T.J*_*der 6

在您的具体情况下,catchWrap看起来像这样:

function catchWrap(originalFunction) {
    return function(req, res, next) {
        try {
            return originalFunction.call(this, req, res, next);
        } catch (e) {
            next(e);
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

这将返回一个新函数,当调用它时,将使用您的catch包装器调用原始函数.关键部分是它创建并返回一个function(return function(req, res, next) { ... };)和这一行:

return originalFunction.call(this, req, res, next);
Run Code Online (Sandbox Code Playgroud)

Function#call调用给定的函数说出this在调用期间使用的内容(在上面我们传递了this我们收到的内容)以及在调用中使用的参数.

你在展示时使用它:

app.get(routes.test, catchWrap(actualRouteHandler));
Run Code Online (Sandbox Code Playgroud)

或者,如果您希望将实际处理程序定义为匿名函数:

app.get(routes.test, catchWrap(function(req, res, next) {
    // ...handler code here...
}));
Run Code Online (Sandbox Code Playgroud)

catchWrap是特定于您的情况,因为您想要next(e)抛出异常调用."在另一个函数中包装此函数" 的通用形式如下:

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
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

arguments是由JavaScript提供的伪数组,包括调用当前函数的所有参数.Function#apply就像Function#call,除了你给参数使用数组(或伪数组)而不是离散.