[英]how to let @ExceptionHandlers handle specific exceptions before defaulting to an Exception handler for any Runtime error?
我想使用@ExceptionHandler來處理任何Hibernate異常。 如果該異常不是Hibernate異常,則針對運行時錯誤的@ExceptionHandler會處理該異常。
問題是,運行時異常始終優先於Hibernate異常處理程序。 意思是,發生的任何休眠異常都由常規的運行時異常處理程序處理。
如何確保Hibernate異常由其異常處理程序處理,而不是由Runtime異常處理?
'@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";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.