Loading...
Searching...
No Matches
Operation Exceptions

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.

void example(mongocxx::database db) {
EXPECT(db.name() == "db");
// The `getParameter` command can only be run in the `admin` database.
auto cmd = bsoncxx::from_json(R"({"getParameter": "*"})");
// This error handling pattern applies to all commands which may throw a
// `mongocxx::operation_exception` exception.
try {
auto reply = db.run_command(cmd.view());
EXPECT(false && "should not reach this point");
} catch (mongocxx::exception const& ex) {
EXPECT(ex.code().category() == mongocxx::server_error_category());
EXPECT(ex.code().value() == 13); // Unauthorized
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)

void example(mongocxx::database db) {
EXPECT(db.name() == "db");
// The `getParameter` command can only be run in the `admin` database.
auto cmd = bsoncxx::from_json(R"({"getParameter": "*"})");
// This error handling pattern applies to all commands which may throw a
// `mongocxx::operation_exception` exception.
try {
auto reply = db.run_command(cmd.view());
EXPECT(false && "should not reach this point");
} catch (mongocxx::operation_exception const& ex) {
EXPECT(ex.code().category() == mongocxx::server_error_category());
EXPECT(ex.code().value() == 13); // Unauthorized
EXPECT(std::strstr(ex.what(), "admin") != nullptr);
if (auto server_error_opt = ex.raw_server_error()) {
bsoncxx::document::view server_error = server_error_opt->view();
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"]);
// ... other error fields.
}
}
}