【问题标题】:how to let @ExceptionHandlers handle specific exceptions before defaulting to an Exception handler for any Runtime error?在默认为任何运行时错误的异常处理程序之前,如何让@ExceptionHandlers 处理特定异常?
【发布时间】:2019-09-14 00:19:23
【问题描述】:

我想使用 @ExceptionHandler 来处理任何 Hibernate 异常。如果异常不是 Hibernate 异常,则运行时错误的 @ExceptionHandler 会处理该异常。

问题是,运行时异常总是优先于 Hibernate 异常处理程序。这意味着,任何发生的休眠异常都将由通用运行时异常处理程序处理。

如何确保 Hibernate 异常由其异常处理程序处理,而不是由运行时异常处理?

    '@ExceptionHandler(HibernateException.class)
public String handleHibernateException(HibernateException exc, Model theModel) {

    String message = "An error has occured: " + exc.getLocalizedMessage() + "\n" + exc.getCause().toString()
            + "\r\n";

    myLogger.warning(message);

    theModel.addAttribute("exception", message);

    return "testing";
}

// handle any other runtime/unchecked exception and log it

@ExceptionHandler(RuntimeException.class)
public String handleRuntimeExceptions(RuntimeException exc, Model theModel) {

    String message = "An error has occured: " + exc.getLocalizedMessage() + "\n" + exc.getCause().toString()
            + "\r\n";
    myLogger.warning(message);

    theModel.addAttribute("exception", message);

    return "testing";
}'

【问题讨论】:

    标签: java spring hibernate exception


    【解决方案1】:

    您可以通过以下方式检查异常是否是 HibernateException 的实例:

    @ExceptionHandler(RuntimeException.class)
    public String handleRuntimeExceptions(RuntimeException exc, Model theModel) {
        if (exc instanceof HibernateException) {
            return handleHibernateException((HibernateException) exc.getCause(), theModel);
        } else if (exc.getCause() instanceof HibernateException) {
            HibernateException hibernateException = (HibernateException) exc.getCause();
            return handleHibernateException(hibernateException, theModel);
        }
        String message = "An error has occurred: " + exc.getLocalizedMessage() + "\n" + exc.getCause().toString() + "\r\n";
        myLogger.warning(message);
        theModel.addAttribute("exception", message);
        return "testing";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-05
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      相关资源
      最近更新 更多