How to handle exceptions thrown by database and collection operations.
As a Regular Exception
- Warning
- The mongocxx::server_error_category error category is overloaded (CXX-834). The error code value may belong to the server, mongoc, or libmongocrypt depending on the context. Use error code values with caution.
EXPECT(db.
name() ==
"db");
try {
EXPECT(false && "should not reach this point");
EXPECT(ex.code().value() == 13);
EXPECT(std::strstr(ex.what(), "admin") != nullptr);
}
}
As an Operation Exception
- Note
- Using mongocxx::exception for error handling is recommended for forward compatibility. (CXX-2377)
EXPECT(db.
name() ==
"db");
try {
EXPECT(false && "should not reach this point");
EXPECT(ex.code().value() == 13);
EXPECT(std::strstr(ex.what(), "admin") != nullptr);
EXPECT(server_error["ok"]);
EXPECT(server_error["ok"].get_double().value == 0.0);
EXPECT(server_error["code"]);
EXPECT(server_error["code"].get_int32().value == ex.code().value());
EXPECT(server_error["codeName"]);
EXPECT(server_error["errmsg"]);
}
}
}