使用 Node.js / Express 是否有可能 next() 来自 IIFE 内部的错误并前进到错误处理中间件?

Using Node.js / Express is it possible to next() an error from inside an IIFE and advance to the error handling middleware?

问题: 使用 Express 是否有可能 return 来自 IIFE 内部的错误并前进到我的错误处理中间件?
背景: IIFE is used to create an async container to wrap await 语句。我看不出解决这个问题的方法,我想知道我是否完全使用了错误的基本模式。

简化示例:

app.get('/', function(req, res, next) {

    (async function() {

        try {
            let example = await someLogic(x);
        } catch(err) {
            return next(new Error('oops'));
        } 
    })();

    console.log('main endpoint');
});

app.use(function(err, req, res, next) {

    console.log('my error', err.message);
});

Using Express is it possible to return an error from inside an IIFE and advance to my error handling middleware?

是的,效果很好。它会调用 next(err) 就好了。但是,您的 return 将 return 仅来自 IIFE,并且 try/catch 之后的其余请求处理程序仍将执行(不确定您是否想要)。


仅供参考,将请求处理程序声明为 async 可能更简单,然后您不需要 IIFE 包装器:

app.get('/', async function(req, res, next) {

    try {
        let example = await someLogic(x);

        console.log('main endpoint');
        // send some response here

    } catch(err) {
        return next(new Error('oops'));
    } 
});