Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 615
CynicalProgrammer Avatar asked Nov 03 '14 15:11

CynicalProgrammer


1 Answers

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.

like image 82
Craig Wilson Avatar answered Oct 18 '22 11:10

Craig Wilson