gpt4 book ai didi

Java 未捕获 lambda 引发的未经检查的异常

转载 作者:行者123 更新时间:2023-12-02 04:26:29 26 4
gpt4 key购买 nike

我有一个函数,它接受两个 lambda 作为参数。这些函数抛出一个特定的未经检查的异常,我希望该函数捕获该异常:

    /**
*
* @param insert function to insert the entity
* @param fetch function to fetch the entity
* @param <T> type of entity being inserted
* @return
*/
@Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED)
public <T> T getOrInsertWithUniqueConstraints(Supplier<Optional<T>> fetch, Supplier<T> insert) {
try {
Optional<T> entity = fetch.get();
T insertedEntity = entity.orElseGet(insert);
return insertedEntity;
}
catch (Exception e){
//I expect/want the exception to be caught here,
//but this code is never called when debugging
Optional<T> entityAlreadyInserted = fetch.get();
return entityAlreadyInserted.get();
}
}

在属于另一个事务的函数中调用:

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
...
try {
Player persistedPlayer = insertOrGetUtil.getOrInsertWithUniqueConstraints(
() -> playerRepository.findOne(newPlayer.getUsername()),
//this lambda throws the unchecked DataIntegrityViolationException
() -> playerRepository.save(newPlayer)
);
}
catch (Exception e){
//the exception is caught here for some reason...
}

我是否误解了 Java lambda 的工作原理?另外值得注意的是,代码使用了 Spring 的 @TransactionalCrudRepository

最佳答案

异常实际上是在提交事务时发生的,它发生在方法返回之后。为了解决这个问题,我使用 EntityManager#flush() 来触发方法返回之前提交时发生的任何异常:

    @Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED)
public <T> T getOrInsertWithUniqueConstraints(Supplier<Optional<T>> fetch, Supplier<T> insert) {
try {
Optional<T> entity = fetch.get();
T insertedEntity = entity.orElseGet(insert);
entityManager.flush();
return insertedEntity;
}
catch (PersistenceException e){
DataAccessException dae = persistenceExceptionTranslator.translateExceptionIfPossible(e);
if (dae instanceof DataIntegrityViolationException){
Optional<T> entityAlreadyInserted = fetch.get();
return entityAlreadyInserted.get();
}
else {
throw e;
}
}
}

关于Java 未捕获 lambda 引发的未经检查的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56606466/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com