中间件并不是等待期待的承诺拒绝



我正在使用nodejs。

我有一个诺言,几秒钟后请求。但是我的中间件并没有遇到错误,而是毫无疑问。

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. 我不想在每个中间件中添加尝试/捕获。(路线===中间件)
  2. 我想使用异步/等待
  3. 使用uncaughtexception对我没有帮助,因为我无法在路线中向用户返回响应。

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

这应该帮助您

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);
 });

相关内容

最新更新