【问题标题】:Promise rejects with await are not catches by the Middleware [duplicate]带有等待的承诺拒绝不是中间件的捕获[重复]
【发布时间】:2018-05-09 06:15:17
【问题描述】:

我正在使用 Nodejs。

我有一个承诺,几秒钟后请求。 但是我的中间件没有捕捉到错误,但是 uncaughtException 捕捉到了。

router.all('/incaseoferror', async(req, res, next) => {

    const promise = await new Promise(function (resolve, reject) {
        setTimeout(function () {
            reject(new Error('this is a test err, the error-middleware NOT catch and it NOT OKAY'));
        }, 3000);
    });

  //  throw new Error('test error - the error-middleware catch it and that okay');
});

function clientErrorHandler(err, req, res, next) {

    console.log('in clientErrorHandler', err);
//but not catch the promise error!

});

process.on('uncaughtException', function (error) {

    // the error is catch here..
});

问题出在: 假设我有另一个库的登录功能,它给了我一个承诺。 函数中的某些内容失败了,我无法在我的错误中间件中捕获错误以向用户响应请求失败。

  1. 我不想在每个中间件中添加 try/catch。 (路由===中间件)
  2. 我想使用异步/等待
  3. 使用 uncaughtException 对我没有帮助,因为我无法在路由中向用户返回响应。

那我该怎么办?有什么想法吗?

【问题讨论】:

  • 也许是时候从 Express 切换到 Koa...

标签: javascript node.js express asynchronous error-handling


【解决方案1】:

这应该对你有帮助

await new Promise(function (resolve, reject) {
        setTimeout(function () {
            reject(new Error('this is a test err, the error-middleware NOT catch and it NOT OKAY'));
        }, 3000);
    })
.catch((err) => {
    clientErrorHandler(err);
 });

【讨论】:

  • 没有。我也想使用异步/等待。不是然后/赶上。
  • 我正在使用 async/await 来获得承诺;您的意思是即使捕获错误也要使用 async/await?
  • 不,当我执行throw new Error 并且中间件捕获时,我只是希望有相同的行为。所以对于承诺拒绝。
  • 所以,即使我的答案的前半部分也不能满足您的要求。我说的对吗?
  • @ShlomiLevi 我已经更新了答案。
猜你喜欢
  • 2018-11-20
  • 1970-01-01
  • 1970-01-01
  • 2020-08-20
  • 1970-01-01
  • 2017-04-12
  • 1970-01-01
  • 2019-12-16
相关资源
最近更新 更多