我怎样才能用另一个函数包装每个快速路由处理程序

How can I wrap every every express route handler with another 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 传递正确参数(req、res、next)并且仍然具有该功能的方法。我需要 return 函数或类似的东西吗?

编辑:我认为可能有库可以执行此操作,但我们无法访问这段代码中的实际 express 应用程序。

以下简单方法可用于设置通用错误处理程序 -

第 1 步:在注册路由后编写错误处理程序。因此,例如,如果您像这样注册多条路线:

config.getGlobbedFiles('./app/routes/modules/**/*.js').forEach(function (routePath) {
        require(path.resolve(routePath))(app);
    });

注册路由后,您可以设置一个通用的错误处理程序-

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)".

在您的特定情况下,catchWrap 将如下所示:

function catchWrap(originalFunction) {
    return function(req, res, next) {
        try {
            return originalFunction.call(this, req, res, next);
        } catch (e) {
            next(e);
        }
    };
}

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

return originalFunction.call(this, req, res, next);

Function#call 调用给定的函数,说明在调用期间使用什么作为 this (在上面我们传递了我们收到的 this )和要在打电话。

你会像你展示的那样使用它:

app.get(routes.test, catchWrap(actualRouteHandler));

或者如果您更愿意将实际处理程序定义为匿名函数:

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

catchWrap 特定于您的情况,因为您希望在抛出异常时调用 next(e)。 "wrap this function in another function" 的 generic 形式是这样的:

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 就像 Function#call,除了你给出的参数用作数组(或伪数组)而不是离散的。