简体   繁体   English

ExpressJS中间件还捕获错误?

[英]ExpressJS middleware that also catches errors?

I'm writing middleware that I'm applying at the route level, like so: 我正在编写要在路由级别应用的中间件,如下所示:

router.get('/foo', myMiddleware, (req, res) => { ... });

so I can do some stuff with the request. 所以我可以根据要求做一些事情。 But I also need to catch errors to do some special handling. 但是我还需要捕获错误才能进行一些特殊处理。 I know I can add a handler afterwards like this: 我知道以后可以像这样添加处理程序:

... (req, res) => { ... }, myErrorHandler);

and it'll get called just fine. 它会被称为很好。

But my question is, is there any way to have a single piece of middleware that can do all of this so I don't need two points of integration? 但是我的问题是,有没有办法拥有一个可以完成所有这些工作的中间件,所以我不需要两点集成? I tried calling req.on('error', (err) => { ... }) within my middleware but it never seems to be called. 我尝试在中间件中调用req.on('error', (err) => { ... }) ,但似乎从未调用过。

Express comes with a built-in error handler that takes care of any errors that might be encountered in the app. Express带有内置的错误处理程序 ,可处理应用程序中可能遇到的任何错误。 This default error-handling middleware function is added at the end of the middleware function stack. 默认的错误处理中间件功能已添加到中间件功能堆栈的末尾。

// Router
router.get('/foo', myMiddleware, (req, res) => { ... });

// Router Error Handler
router.use(function (err, req, res, next) {

});

I ended up solving this by writing a helper function that wraps the actual handler. 我最终通过编写包装实际处理程序的辅助函数来解决了这个问题。 It looks like this: 看起来像这样:

function checkPage(handler: express.RequestHandler) {
    return async (req: express.Request, res: express.Response, next: express.NextFunction) => {
        let _write = res.write;
        res.write = chunk => {
            if (req.query.verbose) {
                return _write.call(res, `<p>${chunk}</p>`);
            } else {
                return true;
            }
        }

        try {
            await handler(req, res, next);
            res.write('<hr/><p style="color:green;"><b>happy</b></p>');
        } catch (err) {
            res.write(`<p style="color:red;">${err}</p>`);
            res.write('<hr/><p style="color:red;"><b>SAD!</b></p>')
        }

        res.end();
    }
}

Then in my route handler, I just use it like so: 然后在我的路由处理程序中,就像这样使用它:

router.get('/foo', checkPage(async (req, res, next) => {
    ...
    res.write('stuff');
    ...
}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM