猿问

在默认为任何运行时错误的异常处理程序之前,如何让@ExceptionHandlers 处理特定异常?

我想使用 @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";

}'


守着一只汪
浏览 131回答 1
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";}
随时随地看视频慕课网APP

相关分类

Java
我要回答