diff --git a/src/main/com/mongodb/CommandResult.java b/src/main/com/mongodb/CommandResult.java index 5ba432452af..fed01a7b005 100644 --- a/src/main/com/mongodb/CommandResult.java +++ b/src/main/com/mongodb/CommandResult.java @@ -70,7 +70,9 @@ public MongoException getException() { if ( !ok() ) { // check for command failure return new CommandFailureException( this ); } else if ( hasErr() ) { // check for errors reported by getlasterror command - if (getCode() == 11000 || getCode() == 11001 || getCode() == 12582) { + String err = getErr(); + if (getCode() == 11000 || getCode() == 11001 || getCode() == 12582 || + err.startsWith("E11000") || err.startsWith("E11001")) { return new MongoException.DuplicateKey(this); } else { @@ -92,13 +94,17 @@ int getCode() { return code; } + String getErr() { + return (String) get("err"); + } + /** * check the "err" field * @return if it has it, and isn't null */ boolean hasErr(){ - Object o = get( "err" ); - return (o != null && ( (String) o ).length() > 0 ); + String o = getErr(); + return (o != null && !o.isEmpty()); } /** diff --git a/src/test/com/mongodb/CommandResultTest.java b/src/test/com/mongodb/CommandResultTest.java index 6bee150ef62..792d6cc0f6c 100644 --- a/src/test/com/mongodb/CommandResultTest.java +++ b/src/test/com/mongodb/CommandResultTest.java @@ -57,4 +57,21 @@ public void testCommandFailure() throws UnknownHostException { assertEquals(5000, e.getCode()); } } + + /** + * mongoS return an "err" but don't return a "code" for duplicate key errors + */ + @Test + public void testCommandDuplicateKeyWithoutCode() throws UnknownHostException { + CommandResult commandResult = new CommandResult(new ServerAddress("localhost")); + final DBObject result = new BasicDBObject("ok", 1.0).append("err", "E11000 duplicate key error index"); + commandResult.putAll(result); + assertEquals(MongoException.DuplicateKey.class, commandResult.getException().getClass()); + try { + commandResult.throwOnError(); + fail("Should throw"); + } catch (MongoException.DuplicateKey e) { + assertEquals(commandResult, e.getCommandResult()); + } + } }