Augustin Popa
Augustin Popa

Reputation: 1543

Check whether insertions were successful (MongoDB C# driver)

Suppose "doc" is some document I want to insert into a MongoDB collection and "collection" is the collection I am inserting the document into.

I have something like the following:

try
{
    WriteConcern wc = new WriteConcern();
    wc.W = 1;
    wc.Journal = true;

    WriteConcernResult wcResult = collection.Insert(doc, wc);

    if (!string.IsNullOrWhiteSpace(wcResult.ErrorMessage) || !wcResult.Ok)
    {
        return ErrorHandler(...); 
    }
    else
    {
        return SuccessFunction(...); 
    }
}
catch (Exception e)
{
    return e.Message;
}

Basically, if the insertion fails for any reason (other than hardware no longer working properly) I want to handle it (through the ErrorHandler function or the catch clause), while if it succeeds I want to call SuccessFunction.

My question: Is the above code sufficient for error checking purposes? In other words, will all failed insertions be caught, so that SuccessFunction is never called in those situations?

Upvotes: 7

Views: 6074

Answers (1)

Craig Wilson
Craig Wilson

Reputation: 12624

You don't even need to do any checking. collection.Insert will throw an exception if the write was not successful when you are using any write concern other than unacknowledged.

If you want to know if an error occured, you need to catch a WriteConcernException.

Upvotes: 15

Related Questions