mongocxx 3.x insert will throw exception when duplicate key found

51 views
Skip to first unread message

li ning

unread,
Apr 20, 2016, 2:59:39 AM4/20/16
to mongodb-user
Not way to disable exception? Why not set error code in return value? Even the return type is a dedicated type "result"?

Andrew Morrow

unread,
Apr 24, 2016, 7:18:16 PM4/24/16
to mongod...@googlegroups.com

The C++11 driver throws exceptions to indicate errors that the user must handle. Exceptions require the programmer to deal with them - return values may be ignored.

Note that in C++11 (or particularly C++14) you can easily transmute a throwing function into one that returns values, if you are so inclined:

const auto make_nothrow = [](auto callable) {
    return [callable(std::move(callable))](auto ...args) noexcept {
        try {
            return std::make_tuple(
                std::experimental::make_optional(
                    callable(args...)
                ),
                std::exception_ptr()
            );
        }
        catch(...) {
            return std::make_tuple(
                std::experimental::optional<decltype(callable(args...))>(),
                std::current_exception()
            );
        }
    };
};

double throws(int x, double y) {
    if (x != y)
        throw std::runtime_error("I'm an exception");
    return x + y;
}

int main(int argc, char* argv[]) {
    auto doesnt_throw = make_nothrow(throws);

    auto result1 = doesnt_throw(argc, 1.0);
    std::cout << *std::get<0>(result1) << std::endl;

    auto result2 = doesnt_throw(argc, 2.0);

    return EXIT_SUCCESS;
}

I've used C++14 to reduce the template verbiage here, and std::optional and std::tuple here to simulate a variant type, but if you have a proper variant like boost::variant, you can do even better.

Thanks,
Andrew





On Wed, Apr 20, 2016 at 2:59 AM, li ning <li.ni...@gmail.com> wrote:
Not way to disable exception? Why not set error code in return value? Even the return type is a dedicated type "result"?

--
You received this message because you are subscribed to the Google Groups "mongodb-user"
group.
 
For other MongoDB technical support options, see: https://docs.mongodb.org/manual/support/
---
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongodb-user...@googlegroups.com.
To post to this group, send email to mongod...@googlegroups.com.
Visit this group at https://groups.google.com/group/mongodb-user.
To view this discussion on the web visit https://groups.google.com/d/msgid/mongodb-user/3f4b42f8-9a5b-464b-9b27-017c05ebb832%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages