2017-06-13 83 views
0

當我嘗試捕獲DataIntegrityViolationException並將其轉換爲我的自定義異常時,catch塊不會執行。Spring TransactionTemplate不處理異常

正如我使用的代碼從一個這樣的示例: guide

結果,ServicePointRepository拋出DataIntegrityViolationException是在我的控制器層處理,並且在運行時代碼似乎是避免catch塊。

我在做什麼錯?

這是PersistenceService代碼:

@Autowired 
private ServicePointRepository servicePointRepository; 

@Autowired 
private BusinessExceptionFactory businessExceptionFactory; 

@Autowired 
private TransactionTemplate transactionTemplate; 

@Override 
public String save(final ServicePointDTO servicePointDTO) { 
    final ServicePointEntity servicePointEntity = mapToEntity(servicePointDTO); 
    return transactionTemplate.execute(status -> { 
     try { 
      return servicePointRepository.save(servicePointEntity).getId().toString(); 
     } catch (DataIntegrityViolationException e) { 
      throw businessExceptionFactory.createBusinessException(AlreadyExistException.class, CommonError.ALREADY_EXIST); 
     } 
    }); 
} 

回答

0

這是正確的方法:

@Override 
public String save(final ServicePointDTO servicePointDTO) { 
    final ServicePointEntity servicePointEntity = mapToEntity(servicePointDTO); 
    try { 
     return transactionTemplate.execute(status -> servicePointRepository.save(servicePointEntity).getId().toString()); 
    } catch (DataIntegrityViolationException e) { 
     throw businessExceptionFactory.createBusinessException(AlreadyExistException.class, CommonError.ALREADY_EXIST); 
    } 
} 

此外,這種方法不應該被標記爲@Transactional

0

您需要定義PersistenceExceptionTranslationPostProcessor後處理器用邏輯代理您的存儲庫,將專有異常轉換爲Spring DataAccessException hie rachy。還記得與@Repository註解來標記庫對它們進行檢測和代理

@Bean 
public PersistenceExceptionTranslationPostProcessor exceptionTranslatorPostProcessor(){ 
    return new PersistenceExceptionTranslationPostProcessor(); 
} 

或等值的XML