gpt4 book ai didi

java - 如何从事务性 Spring 服务中抛出自定义异常?

转载 作者:行者123 更新时间:2023-11-30 10:28:30 25 4
gpt4 key购买 nike

我有这个 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);
}
}


}

该服务使用这个 Spring Data 存储库:

@Repository
public interface ConsorcioRepository extendsCrudRepository<Consorcio, Integer> {


}

我正在从 spring Controller 调用服务:

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

但是我在 Controller 中得到的异常是:org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction;嵌套异常是 javax.persistence.RollbackException: Transaction marked as rollbackOnly而不是 DuplicatedCodeException 我在服务中抛出。我需要确定异常类型,以便提供自定义友好的用户消息。

最佳答案

还有你的 DuplicatedCodeException , BusinessException 应该是运行时异常,或者为方法 saveBank 添加:

@Transactinal(rolbackFor={BusinessException.class,DuplicatedCodeException.,class })

在其他情况下,spring 不会回滚事务。

来自 Spring 文档:

While the EJB default behavior is for the EJB container to automatically roll back the transaction on a system exception (usually a runtime exception), EJB CMT does not roll back the transaction automatically on an application exception (that is, a checked exception other than java.rmi.RemoteException). While the Spring default behavior for declarative transaction management follows EJB convention (roll back is automatic only on unchecked exceptions), it is often useful to customize this.

关于java - 如何从事务性 Spring 服务中抛出自定义异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44575617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com