2017-06-13 10 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

これが正しい方法である:あなたが定義する必要も、この方法は@Transactional

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); 
    } 
} 

PersistenceExceptionTranslationPostProcessor独自の例外をSpringに変換するロジックを使用してリポジトリをプロキシするためのポストプロセッサDataAccessException hieラッキー。また、それらが検出され、XML

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

または同等のプロキシされるために@Repository注釈を使用してリポジトリをマークすることを忘れないでください

関連する問題