【问题标题】:MongoDB C++ driver not throwing connection errorMongoDB C++ 驱动程序不抛出连接错误
【发布时间】:2012-01-09 23:57:45
【问题描述】:

这是我的代码-

DBClientBase *conn = NULL;
string err_msg;
ConnectionString cs = ConnectionString::parse(connString, err_msg);

if (!cs.isValid()) {
   throw "bad: " + err_msg;
}

try {
  conn = cs.connect(err_msg);
}
catch (DBException &e) {
   cout << "caught " << err_msg << endl;
   return 1;
}

if (!conn) {
   cout << "Unable to connect to DB" << endl;
   return 1;
}

如果无法访问数据库,我希望 MongoDB 会抛出异常。但是,我发现if (!conn) 越来越满意了。

为什么

catch (DBException &e) {
   cout << "caught " << err_msg << endl;
   return 1;
}

块不起作用?

【问题讨论】:

    标签: c++ exception mongodb exception-handling try-catch


    【解决方案1】:

    来自the current trunk sourceConnectionString::connect 似乎只在字符串本身无效时抛出异常(并且您已经知道它不是,从您的第一个条件语句)。

    它只是返回一个 NULL 指针并在所有其他情况下设置errMsg

    为你辩护,我在任何地方都找不到这方面的记录;我只能找到a very basic example of connect

    string err_msg;
    ConnectionString cs = ConnectionString::parse(connString, err_msg);
    
    if (!cs.isValid()) {
       throw "bad: " + err_msg;
    }
    
    DBClientBase* conn = cs.connect(err_msg);
    
    if (!conn) {
       cout << "Unable to connect to DB: " << err_msg << endl;
       return 1;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-25
      • 1970-01-01
      • 1970-01-01
      • 2012-09-16
      • 2023-04-01
      • 1970-01-01
      • 2017-11-07
      • 1970-01-01
      相关资源
      最近更新 更多