Java源码示例:com.mongodb.ErrorCategory
示例1
@Override
public void create(final Entity entity) throws EntityStorageException {
requireNonNull(entity);
try {
final boolean hasDuplicate = detectDuplicates(entity);
if (!hasDuplicate) {
mongo.getDatabase(ryaInstanceName)
.getCollection(COLLECTION_NAME)
.insertOne( ENTITY_CONVERTER.toDocument(entity) );
} else {
throw new EntityNearDuplicateException("Duplicate data found and will not be inserted for Entity with Subject: " + entity);
}
} catch(final MongoException e) {
final ErrorCategory category = ErrorCategory.fromErrorCode( e.getCode() );
if(category == ErrorCategory.DUPLICATE_KEY) {
throw new EntityAlreadyExistsException("Failed to create Entity with Subject '" + entity.getSubject().getData() + "'.", e);
}
throw new EntityStorageException("Failed to create Entity with Subject '" + entity.getSubject().getData() + "'.", e);
}
}
示例2
@Override
public void create(final Event event) throws EventStorageException {
requireNonNull(event);
try {
mongo.getDatabase(ryaInstanceName)
.getCollection(COLLECTION_NAME)
.insertOne(EVENT_CONVERTER.toDocument(event));
} catch(final MongoException e) {
final ErrorCategory category = ErrorCategory.fromErrorCode( e.getCode() );
if(category == ErrorCategory.DUPLICATE_KEY) {
throw new EventAlreadyExistsException("Failed to create Event with Subject '" + event.getSubject().getData() + "'.", e);
}
throw new EventStorageException("Failed to create Event with Subject '" + event.getSubject().getData() + "'.", e);
}
}
示例3
public boolean acquireLock(MongoDatabase db) {
Document insertObj = new Document(KEY_PROP_NAME, LOCK_ENTRY_KEY_VAL).append("status", "LOCK_HELD");
// acquire lock by attempting to insert the same value in the collection - if it already exists (i.e. lock held)
// there will be an exception
try {
db.getCollection(lockCollectionName).insertOne(insertObj);
} catch (MongoWriteException ex) {
if (ex.getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
logger.warn("Duplicate key exception while acquireLock. Probably the lock has been already acquired.");
}
return false;
}
return true;
}
示例4
/**
* Checks if the given error is caused due to duplicate keys.
*
* @param error The error to check.
* @return {@code true} if the given error is caused by duplicate keys.
* @throws NullPointerException if the error is {@code null}.
*/
public static boolean isDuplicateKeyError(final Throwable error) {
Objects.requireNonNull(error);
if (error instanceof MongoException) {
final MongoException mongoException = (MongoException) error;
return ErrorCategory.fromErrorCode(mongoException.getCode()) == ErrorCategory.DUPLICATE_KEY;
}
return false;
}