我有這個春季服務:如何從事務性的Spring服務中拋出自定義異常?
@Service
@Transactional
public class ConsorcioServiceImpl implements ConsorcioService {
...
@Autowired
private ConsorcioRepository consorcioRepository;
@Override
public void saveBank(Consorcio consorcio) throws BusinessException {
try {
consorcioRepository.save(consorcio);
}
catch(DataIntegrityViolationException divex) {
if(divex.getMessage().contains("uq_codigo")) {
throw new DuplicatedCodeException(divex);
}
else {
throw new BusinessException(dives);
}
}
catch (Exception e) {
throw new BusinessException(e);
}
}
}
該服務使用這個春天數據倉庫:
@Repository
public interface ConsorcioRepository extendsCrudRepository<Consorcio, Integer> {
}
我從彈簧控制器調用服務:
@Controller
@RequestMapping(value = "/bank")
public class BancaController {
@Autowired
private ConsorcioService consorcioService;
@RequestMapping(value="create", method=RequestMethod.POST)
public ModelAndView crearBanca(@Valid BancaViewModel bancaViewModel, BindingResult bindingResult,
RedirectAttributes redirectAttributes) {
ModelAndView modelAndView;
MessageViewModel result;
try {
consorcioService.saveBank(bancaViewModel.buildBanca());
result = new MessageViewModel(MessageType.SUCESS);
redirectAttributes.addFlashAttribute("messageViewModel", result);
modelAndView = new ModelAndView("redirect:/banca/crear");
return modelAndView;
} catch (Exception e) {
result = new MessageViewModel(MessageType.ERROR);
modelAndView = new ModelAndView("crear-bancas");
modelAndView.addObject("messageViewModel", result);
return modelAndView;
}
}
但異常我得到的控制器是:org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly
而不是DuplicatedCodeException
我投入服務。我需要確定異常的類型,以便我可以提供自定義友好的用戶消息。
我從'RuntimeException',而不是'Exception'繼承和行爲是爲我預期。 –