DATAMONGO-318 - Don't throw exceptions for updates not affecting any documents.

Throwing an exception if an update does not affect any documents doesn't make sense in all cases. Removed throwing an exception by default but made the relevant method (handleAnyWriteResultErrors(…)) protected so that subclasses might override this behavior.
This commit is contained in:
Oliver Gierke
2011-12-06 15:15:13 +01:00
parent 7da0fcdd0c
commit 75b7aff80a
2 changed files with 10 additions and 17 deletions

View File

@@ -1468,27 +1468,24 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware {
* Current implementation logs errors. Future version may make this configurable to log warning, errors or throw
* exception.
*/
private void handleAnyWriteResultErrors(WriteResult wr, DBObject query, String operation) {
protected void handleAnyWriteResultErrors(WriteResult wr, DBObject query, String operation) {
if (WriteResultChecking.NONE == this.writeResultChecking) {
return;
}
String error = wr.getError();
int n = wr.getN();
if (error != null) {
String message = "Execution of '" + operation + (query == null ? "" : "' using '" + query.toString() + "' query")
+ " failed: " + error;
String message = String.format("Execution of %s%s failed: %s", operation, query == null ? "" : "' using '"
+ query.toString() + "' query", error);
if (WriteResultChecking.EXCEPTION == this.writeResultChecking) {
throw new DataIntegrityViolationException(message);
} else {
LOGGER.error(message);
}
} else if (n == 0) {
String message = "Execution of '" + operation + (query == null ? "" : "' using '" + query.toString() + "' query")
+ " did not succeed: 0 documents updated";
if (WriteResultChecking.EXCEPTION == this.writeResultChecking) {
throw new DataIntegrityViolationException(message);
} else {
LOGGER.warn(message);
return;
}
}
}

View File

@@ -39,7 +39,6 @@ import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.mongodb.InvalidMongoDbApiUsageException;
import org.springframework.data.mongodb.MongoDbFactory;
@@ -145,7 +144,7 @@ public class MongoTemplateTests {
}
@Test
public void updateFailure() throws Exception {
public void bogusUpdateDoesNotTriggerException() throws Exception {
MongoTemplate mongoTemplate = new MongoTemplate(factory);
mongoTemplate.setWriteResultChecking(WriteResultChecking.EXCEPTION);
@@ -156,10 +155,7 @@ public class MongoTemplateTests {
Query q = new Query(Criteria.where("BOGUS").gt(22));
Update u = new Update().set("firstName", "Sven");
thrown.expect(DataIntegrityViolationException.class);
thrown.expectMessage(endsWith("0 documents updated"));
mongoTemplate.updateFirst(q, u, Person.class);
}
@Test