2017-06-13 3 views
0

Wenn ich versuche, DataIntegrityViolationException abzufangen und es in meine benutzerdefinierte Ausnahme konvertieren, wird catch-Block nicht ausgeführt.Spring TransactionTemplate behandelt keine Ausnahmen

Als Beispiel I-Code von benutzten: guide

Als Ergebnis wirft ServicePointRepositoryDataIntegrityViolationException, die an meiner Controller-Schicht behandelt wird, und der Code während der Laufzeit scheint catch-Block zu vermeiden.

Was mache ich falsch?

Dies ist der Code von 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); 
     } 
    }); 
} 

Antwort

0

ist dies die richtige Methode:

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

auch, sollte diese Methode nicht als @Transactional

0

Sie ein definieren, müssen gekennzeichnet werden PersistenceExceptionTranslationPostProcessor-Postprozessor, um Ihre Repositories mit Logik zu dekonfigurieren, um eine proprietäre Ausnahme in Spring DataAccessException hie zu konvertieren rachy. Denken Sie auch daran Ihre Repositories mit dem @Repository Anmerkung markieren für sie

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

oder Äquivalent in XML

erkannt und proxied werden
Verwandte Themen