简体   繁体   中英

How to handle data type errors with UserException in MongoDB with the C++ driver

Windows 7 64 SP1 MongoDB 2.2.0 C++ driver MSVS 2010

According to:

http://api.mongodb.org/cplusplus/2.2.0/classmongo_1_1_b_s_o_n_element.html#a692f3eecb505eae2181eb938b7680fbe

Double() (and like functions) should "throw a UserException if the element is not of the required type."

My code:

BSONObj a_document = BSON("a_string"<<"A string");

try
{
    a_document["a_string"].Double();
}
catch(mongo::UserException ue)
{
    cout << ue.toString() << endl;
}

But it doesn't get caught. Intead it asserts:

Sun Dec 09 16:04:28 Assertion: 13111:wrong type for field (a_string) 2 != 1
Sun Dec 09 16:04:28 dev: lastError==0 won't report:wrong type for field (a_string) 2 != 1

What am I doing wrong? I want to catch and handle the data type exceptions myself.

Thanks!

My feeling from looking through the cocumentation and headers is that the documentation is inaccurate at this point, or that some option was used that disables exceptions from MongoDB.

Try the following code:

BSONObj a_document = BSON("a_string"<<"A string");

try
{
    a_document["a_string"].Double();
}
catch(mongo::UserException& ue)
{
    cout << "UserException: " << ue.toString() << endl;
}
catch(mongo::MsgAssertionException& ex)
{
    cout << "MsgAssertionException: " << ex.toString() << endl;
}
catch(mongo::DBException& ex)
{
    cout << "DBException: " << ex.toString() << endl;
}
catch(std::exception& ex)
{
    cout << "std::exception: " << ex.what() << endl;
}

to see which exception gets actually thrown (if any).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM