java - 无法使用Spring MVC在服务层包装DAO异常

标签 java spring-mvc exception custom-exceptions

我正在尝试使用 Spring MVC 处理自定义异常。 DAO 层异常处理程序由服务层和服务层包装该异常,并由 Spring MVC 的 Controller 异常处理程序处理该异常。以下是我的代码:

@Override
public void saveNewMachineDetails(Machine machine, Configurations configurations) throws DataNotPersist{
logger.info("call service saveNewMachineDetails method");

try{
    machineRepository.saveAndFlush(machine);
}catch(Exception ex){
//  logger.error(ex.getMessage());
    DataNotPersist dataNotPersist =  new DataNotPersist(messageSource.getMessage("code.object.notpersist", null, null), 
            messageSource.getMessage("msg.object.notpersist", new Object[]{"Machine"}, null), ex);
    throw dataNotPersist;
}}

在上面的代码中,DAO 层异常在服务层进行处理,并将该异常包装在自定义异常中并抛出该异常。

在 Web 层中,我配置了异常处理程序来处理异常,但是当引发异常时,处理程序不会捕获异常,我认为是因为我无法用自定义异常包装实际异常。以下是我的异常处理程序代码:

@ControllerAdvice
public class GlobalExceptionHandler {

private Logger logger =    LoggerFactory.getLogger(GlobalExceptionHandler.class);

@ExceptionHandler(value = DataNotPersist.class)
public ModelAndView defaultExceptionHandler(HttpServletRequest request, DataNotPersist ex)throws Exception {
logger.info("In GlobalExceptionHandler");

logger.debug("********* : "+ex.getMessage());

ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("exception", ex);
modelAndView.addObject("url", request.getRequestURL());
modelAndView.setViewName("common/error");
return modelAndView;
}}

最佳答案

在服务层中,当我抛出异常时, Spring 回滚事务并将我的Exception包装到TransactionException中查看。现在我使用我的 Exception 类处理事务回滚,如下所示:

@Override
@Transactional(value="transaction_manager", rollbackFor={DataNotPersist.class})
public void saveNewMachineDetails(Machine machine, Configurations configurations) throws DataNotPersist{
    logger.info("call service saveNewMachineDetails method");

    try{
        machineRepository.saveAndFlush(machine);
    }catch(DataAccessException ex){
        logger.error(ex.getMessage());
        DataNotPersist dataNotPersist =  new DataNotPersist(messageSource.getMessage("code.object.notpersist", null, null), 
                messageSource.getMessage("msg.object.notpersist", new Object[]{"Machine"}, null), ex);
        throw dataNotPersist;
    }}

关于java - 无法使用Spring MVC在服务层包装DAO异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28295684/

相关文章:

java - 使用 OAuth2ClientAuthenticationProcessingFilter 通过 Spring Boot 登录 Google Oauth2

java - 读取iso-8859-1中的特殊字符并获取相同字符的utf-8值

java - 异常后更新 Camel 交换体并继续路线

java - 运行spring boot application error : Cannot instantiate interface org. springframework.context.ApplicationListener

java - 如何修复 CrudRepository.save(java.lang.Object) 在 springboot 中没有访问器方法?

java - 设置 Controller 中的字段以在 Spring 测试中使用

c# - 如果子对象和父对象都抛出异常,如何获取两个异常

java - 从 2.3 升级后通过 Android Studio 2.3.3 安装 apk 的未知失败 (UnsatisfiedLinkError)

java - XML 或 XUL 是 Java GUI 构建的 future 吗?

Wcf异常处理抛出错误