如何将数据传递给异常处理程序?

How to pass data to an exceptionhandler?

我找到了一个教程来管理来自 this site 的异常。所以这是我的处理程序:

@Controller
@RequestMapping("/adminrole")
public class AdminRole {

    ...

    @ExceptionHandler({org.hibernate.exception.ConstraintViolationException.class})
    public ModelAndView handlePkDeletionException(Exception ex) {

        ModelAndView model = new ModelAndView("errorPage");

        model.addObject("message", "customised message with data to display in error page");

        return model;

    }

}

现在我想将一些数据(例如导致异常的主键的列名)传递给处理程序,以便在错误页面中显示自定义消息。那么如何将这些数据传递给处理程序?

要将您自己的数据传递给 @ExceptionHandler 方法,您需要在服务层中捕获 framework exceptions,并通过包装附加数据来抛出您自己的 custom exception

服务层:

public class MyAdminRoleService {
    public X insert(AdminRole adminRole) {
         try {
            //code
         } catch(ConstraintViolationException exe) {
            //set customdata from exception
            throw new BusinessException(customdata);
         }
    }
}

控制器层:

@Controller
@RequestMapping("/adminrole")
public class AdminRole {

    @ExceptionHandler({com.myproject.BusinessException.class})
        public ModelAndView handlePkDeletionException(BusinessException ex) {
            String errorMessage  = ex.getErrorMessage(); 
            ModelAndView model = new ModelAndView("errorPage");

            model.addObject("message", errorMessage);

            return model;

        }
    }

P.S.: 我仅以 ConstraintViolationException 为例,但您可以将相同的概念应用于您想要为其添加额外的任何框架异常数据.