Search code examples
mongo-go

With mongodb-go-driver how do I get the inner exceptions


When I insert into a collection with the new MongoDB Go driver I get a duplicate exception that I can see when spewing it. (mongo.WriteException) multiple write errors:

[{write errors: [{E11000 duplicate key error collection: fhir.documents index: enterprise_id_1 dup key: { : "Cache-37", : "102" }}]}, {}]

How do I get to that inner error to programatically know that it was a duplicate key and I can handle it?


Solution

  • I finally found out how. It should be much simpler to get the basic error codes! Given an error, I check for the number of errors found and currently only care about the first one. Even though the initial error says multiple errors, it only has one. This is really only looking for Insert failures of duplicate or Find errors of not found. If there is an easier way, I would like to know. Until then this is what I am using and it works fine. Duplicate by the way is 11000.

    "Insert with session failed: multiple write errors: [{write errors: [{E11000 duplicate key error collection: test.users index: roi_id_1 dup key: { : \"1\" }}]}, {}]\n"

            var merr mongo.WriteException
            merr = err.(mongo.WriteException)
            log.Errorf("Number of errors: %d", len(merr.WriteErrors))
            errCode := merr.WriteErrors[0].Code