javascript - 中间件不会捕获带有等待的 Promise 拒绝

标签 javascript node.js express asynchronous error-handling

我正在使用 Nodejs。

我有一个 promise ,会在几秒钟后请求。 但我的中间件没有捕获错误,但 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..
});

问题是这样的: 假设我有另一个图书馆的登录功能,它给了我一个 promise 。 函数中出现了某些问题,我无法捕获错误中间件中的错误以向用户提供请求失败的响应。

  1. 我不想在每个中间件中添加 try/catch。 (路由===中间件)
  2. 我想使用 async/await
  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);
 });

关于javascript - 中间件不会捕获带有等待的 Promise 拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47486688/

相关文章:

javascript - jQuery Accordion 内的动态内容(文本区域)

javascript - jQuery 通过按键获取总和总是落后一步

javascript - 在 Node.js 中处理 fatal error 的正确方法

node.js - 连接 MongoDb 失败

javascript - 如何使用 Express.js 将 API 访问限制为仅授权域?

javascript - NodeJS 和 ExpressJS - Javascript 文件加载,但 CSS 文件不加载

JavaScript setInterval 限制?

javascript - 检测失败的插件加载并显示消息

json - Node.js fs错误扩展

mysql - 如何减少 Prisma 选择(或包含)字段代码行