簡體   English   中英

未捕獲由lambda拋出的Java未經檢查的異常

[英]Java unchecked exception thrown by lambda is not caught

我有一個函數,它將兩個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 lambdas是如何工作的嗎? 另外值得注意的是代碼使用的是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;
            }
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM