3

I am developing an application which uses MongoDB, and one of my fields must be unique. This field is calculated by the application based on another value in the DB. If I am running multiple instances of the application, however, I can imagine the applications calculating the same value.

In this case, I would like to catch the exception, recalculate the value, and try again. Unfortunately, the exception raised seems to be a simple MongoWriteException. It seems to me that the only way I will know that it is due to the duplicate key issue is based on the exception message, but parsing and making use of the message really doesn't feel right. Are there any other options?

1 Answer 1

4

You can check the ErrorCategory of the error inside the MongoWriteException and confirm it was due to a duplicate key using getCategory():

catch(MongoWriteException ex) {
    if(ex.getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
        //handle duplicate key error
    } else {
        //do something else...
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.