c++ 驱动操作 Mongodb 查询超时异常如何捕获? 5C

代码如下:

 try
    {
        mongo::DBClientConnection * conn = new DBClientConnection(true, 0, 3);
        if(!conn->isFailed())
        {
            cout<<"-false"<<" type:"<< conn->type()<<endl; 
        }
        else
            cout<<"-true"<<" type:"<< conn->type()<<endl; 
        //初始化连接
        MongoDB_Connect(&conn);

        if(conn->isFailed())
        {
            cout<<"1:连接失败!"<<" type:"<< conn->type()<<endl; 
        }
        else
            cout<<"2:连接成功!"<< conn->toString()<<" type:"<< conn->type()<<endl; 
        BSONArrayBuilder c;
        BSONObjBuilder add,A,B;
        int falg = 401;
        B.append("trans_sub_typecode",falg);
        B.append("discouant_money","0");
        B.append("account_money","0");
        B.append("proxy_money","0");
        c.append("0");
        c.append("0.00");
        B.append("trans_amount",BSON("$nin"<<c.arr()));
        auto_ptr<DBClientCursor> cursor;
        Query query(B.obj());
        try
        {
            cursor = conn->query("e_invoice.issue_park_transactions",query);

        }
        catch (mongo::AssertionException &e1)
        {
            printf("0:捕获异常: %s\n", e1.what());
        }
        catch (mongo::SocketException &e1)
        {
            printf("1:捕获异常: %s\n", e1.what());
        }
        catch (mongo::DBException &e1)
        {
            printf("2:捕获异常: %s\n", e1.what());
        }
        catch (mongo::exception &e1)
        {
            printf("02:捕获异常: %s\n", e1.what());
        }
        catch (...)
        {
            printf("查询失败 数据库数据异常\n");
        }
        if(cursor.get() == NULL)
        {
            cout<<"--返回为NULL:"<< conn->type()<<endl;  
        }

        if(conn->isFailed())
        {
            cout<<"2:连接失败!"<<" type:"<< conn->type()<<endl; 
        }
        else
            cout<<"2:连接成功!"<< conn->toString()<<" type:"<< conn->type()<<endl; 
    }
    catch (mongo::SocketException &e1)
    {
        printf("3:捕获异常: %s\n", e1.what());
    }
    catch (mongo::DBException &e1)
    {
        printf("3:捕获异常: %s\n", e1.what());
    }
    catch (...)
    {
        printf("3:查询失败 数据库数据异常\n");
    }

执行结果:
图片说明

我想要获取这段异常,有人有了解么?

1个回答

代码第4行 if( ! conn->isFailed()) 应去掉'!', 即改为:
if( conn->isFailed())
这样与执行结果图中第一处红线在逻辑上匹配。

另外try...catch用法可以深入了解下,
可参考https://www.cnblogs.com/MrYuan/p/4800257.html
祝好运!

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐