Java 对于任何运行时错误,如何让@ExceptionHandlers在默认为异常处理程序之前处理特定的异常?
我想使用@ExceptionHandler来处理任何Hibernate异常。如果异常不是Hibernate异常,则运行时错误的@ExceptionHandler将处理该异常 问题是,运行时异常总是优先于Hibernate异常处理程序。这意味着,发生的任何hibernate异常都将由通用运行时异常处理程序处理 如何确保Hibernate异常由其异常处理程序处理,而不是由运行时异常处理Java 对于任何运行时错误,如何让@ExceptionHandlers在默认为异常处理程序之前处理特定的异常?,java,spring,hibernate,exception,Java,Spring,Hibernate,Exception,我想使用@ExceptionHandler来处理任何Hibernate异常。如果异常不是Hibernate异常,则运行时错误的@ExceptionHandler将处理该异常 问题是,运行时异常总是优先于Hibernate异常处理程序。这意味着,发生的任何hibernate异常都将由通用运行时异常处理程序处理 如何确保Hibernate异常由其异常处理程序处理,而不是由运行时异常处理 '@ExceptionHandler(HibernateException.class) public S
'@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";
}'
您可以通过以下方式检查异常是否为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";
}
您可以通过以下方式检查异常是否为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";
}