首页 > 解决方案 > how to let @ExceptionHandlers handle specific exceptions before defaulting to an Exception handler for any Runtime error?

问题描述

I want to use an @ExceptionHandler to handle any Hibernate exceptions. If the exception is not a Hibernate exception, then an @ExceptionHandler for Runtime errors handles the exception.

the problem is, Runtime exception is always taking precedence over the Hibernate exception handler. meaning, any hibernate exception that occurs is being handled by the general Runtime exception handler instead.

How can I ensure that Hibernate exceptions are handled by its exception handler, rather than being handled by Runtime exceptions?

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

标签: javaspringhibernateexception

解决方案


您可以通过以下方式检查异常是否是 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";
}

推荐阅读