如何将被拒绝的承诺转换为异常并将其从 Express 路由处理程序中抛出?

How can I convert a rejected promise to an exception and throw it from an Express route handler?

在我的一个应用程序的路由处理程序中,我正在调用一个 returns Q promise 的方法。我不想使用 .catch 方法处理拒绝,而是希望它被抛出并被我的 Express 应用程序的 catch-all 错误处理程序捕获。

我尝试了 Q 的 done 方法,但它会异步抛出异常,因此它没有被我的万能错误处理程序处理,而是一直向上传播,我的应用程序被终止:

// The route handler 

function index(req, res) {
    dao.findById(id).then(function (data) {
        res.send(data);
    }).done();
}

// The catch all event-handler

function catchAllErrorHandler(err, req, res, next) {
    console.log(err, req, res);
}

// Registration of the catch-all event handler

app.use(catchAllErrorHandler);

错误永远不会进入捕获所有错误处理程序。有没有办法让 catchAllErrorHandler 处理抛出的错误?

I tried Q's done method

这可能是您从 promise 中抛出异常的最佳方法。

but it throws the exception asynchronously

当然可以,promise 总是异步的。您无法确定您的承诺将来是否会拒绝并同步抛出异常...

Is there a way to make the thrown errors get handled by catchAllErrorHandler?

将处理程序显式传递为处理程序:

dao.findById(id).then(function (data) {
    res.send(data);
}).catch(catchAllErrorHandler);

或者,从 Q v1.3 开始,您可以使用 并将 catchAllErrorHandler 放在那里。

这并没有直接回答您的问题,而是展示了另一种实现目标的方法。

express 中的每个中间件处理程序都有签名 (request, response, next)。当前您的 index 函数没有定义 next。

当调用带有参数的 next 时,express 认为该参数是一个错误,并对其进行适当的管理。

因此,在您的情况下,更改您的 index 函数以包含下一个参数,并将 .done() 更改为 .catch(next) 这将在出现任何错误时调用 next,并允许快递处理。

dao.findById(id)
   // Handle success
    .then(function (data) {
        res.send(data);
    })
    // Handle failure
    .catch(next);