最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Node.js:如何从MongoDB中正确捕获异常?

运维笔记admin10浏览0评论

Node.js:如何从MongoDB中正确捕获异常?

Node.js:如何从MongoDB中正确捕获异常?

如果我的try在MongoClients catch函数内部,则不会出现connect错误>


环境

    Linux(薄荷,泰莎)

  • Node.js v10.16.0(将ES6与
  • nodemon
  • 一起使用)MongoClient(来自mongodb npm存储库)

  • 实施例

    如果我尝试这样做:

    try { throw new Error('This is error'); } catch(e) { console.log(`Catched: ${e}`); }

    我得到

    干净的出口

    (很好-可以工作)
  • Catched: Error: This is error [nodemon] clean exit - waiting for changes before restart
    但是这不起作用

    如果我在MongoDB的connect函数中尝试:

    try { MongoClient.connect(config.url, config.options, (err, db) => { if (err) { throw new Error('This is error'); } }); } catch (err) { console.log(`Catched: ${e}`); }

    我得到

    应用程序崩溃

    Error: This is error [nodemon] app crashed - waiting for file changes before starting...
    所以这意味着它没有捕获我的异常。

    问题,如果它在MongoClients连接功能内部,我的尝试不会捕获错误环境Linux(Mint,Tessa)Node.js v10.16.0(将ES6与nodemon结合使用)MongoClient(来自mongodb npm ...

    回答如下:try { let db = await MongoClient.connect(config.url, config.options); } catch (err) { console.log(`Catched: ${err}`); }
    发布评论

    评论列表(0)

    1. 暂无评论