基于SpringMVC的全局異常處理器介紹
近幾天又溫習了一下SpringMVC的運行機制以及原理
我理解的springmvc,是設計模式MVC中C層,也就是Controller(控制)層,常用的注解有@Controller、@RequestMapping、@Autowared、@Component,今天呢,我所要寫的是SpringMVC的全局異常處理器,關聯(lián)的接口有HandlerExceptionResolver(Eclipse用戶可以按Ctrl+Shift+T進行搜索該接口),什么是全局異常處理器?為什么要用它呢?
在企業(yè)開發(fā)中,各種的Runtime異??赡軙屛覀儽罎?,但是還有一部分異常在此之外,因此我們就要捕獲它,然后進行操作提示(將錯誤提示返回到ModelAndView)
下來呢,我貼一部分代碼
首先呢,創(chuàng)建一個自定義的異常類
/**
* @Title: ExceptionCustom.java
* @Description: 本地異常
* @author ChoviWu
* @version V1.0
*/
public class ExceptionCustom extends Exception{
/**
* @Fields serialVersionUID :
*/
private static final long serialVersionUID = 1L;
private String message;
/**
* @return the message
*/
public String getMessage() {
return message;
}
/**
* @param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}
public ExceptionCustom() {
super();
// TODO Auto-generated constructor stub
}
public ExceptionCustom(String message) {
super(message);
this.message = message;
}
}
創(chuàng)建一個全局異常處理器的類,讓它實現(xiàn)HandlerExceptionResolver 接口。相信,基礎好一點的同學可以看出來我代碼的意思(注釋)
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
/**
* @Title: SimpleException.java
* @Description:全局異常處理器
* @author ChoviWu
* @version V1.0
*/
public class SimpleExceptionResolver implements HandlerExceptionResolver {
// 異常對象
ExceptionCustom exceptionCustom = null;
private Logger logger = Logger.getLogger(SimpleExceptionResolver.class
.getSimpleName());
/**
* 全局處理異常
*/
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
//轉化為自定義異常
exceptionCustom = (ExceptionCustom) ex;
//判斷是否是本地異常
if (ex instanceof ExceptionCustom) {
logger.info(ex.getMessage());
} else {
…拋出錯誤
}
//獲取異常信息
String message = exceptionCustom.getMessage();
ModelAndView mv = new ModelAndView();
//將異常返回到Model
mv.addObject("xx", message);
// 指向錯誤頁面
mv.setViewName("error");
return null;
}
}
解釋一下,在判斷一個異常是否是其他異常的時候,先看它是否屬于本地異常(Exception)的exceptionCustom ,如果是本地異常,則拋出本地異常信息
if (ex instanceof ExceptionCustom) {
logger.info(ex.getMessage());
} else {
…拋出錯誤
}
如果不是本地異常,則拋出未知異常
然后從異常里面獲取異常信息,將異常信息返回到MV中,最后轉至頁面,當然嚴謹一點的,會將異常信息添加到數(shù)據(jù)庫中,方便查看
由于本文章只是一個Demo,所以沒有考慮到很多因素
下來,說說配置文件
配置文件,先貼上代碼,然后再做解釋
<!-- 全局異常處理器 --> <bean id="handlerExceptionResolver" class = "xxxx(包名).SimpleExceptionResolver"/>
注意:首先,這個bean將配置在自己的web層.xml(spring-web.xml),當啟動tomcat,加載web.xml后需加載spring-web.xml
之前注入的bean的id我隨便寫了一個名稱,然后spring解析的時候報錯了,
之后看了源碼的時候,才知道原來是這么回事
1SpringMVC 在org.springframework.web.servlet.DispatcherServlet類中聲明了 public static final String HANDLER_EXCEPTION_RESOLVER_BEAN_NAME = "handlerExceptionResolver";
private void initHandlerExceptionResolvers(ApplicationContext context) {
this.handlerExceptionResolvers = null;
if (this.detectAllHandlerExceptionResolvers) {
// Find all HandlerExceptionResolvers in the ApplicationContext, including ancestor contexts.
Map<String, HandlerExceptionResolver> matchingBeans = BeanFactoryUtils
.beansOfTypeIncludingAncestors(context, HandlerExceptionResolver.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerExceptionResolvers = new ArrayList<HandlerExceptionResolver>(matchingBeans.values());
// We keep HandlerExceptionResolvers in sorted order.
OrderComparator.sort(this.handlerExceptionResolvers);
}
}
else {
try {
HandlerExceptionResolver her =
context.getBean(HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver.class);
this.handlerExceptionResolvers = Collections.singletonList(her);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, no HandlerExceptionResolver is fine too.
}
}
看完這段代碼的同學應該就知道為什么把bean 的id 設置成handlerExceptionResolver了吧
HandlerExceptionResolver her =context.getBean(HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver.class);
所以說,全局異常處理器的bean的id不能隨便的設置。
以上這篇基于SpringMVC的全局異常處理器介紹就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
從Mybatis-Plus開始認識SerializedLambda的詳細過程
這篇文章主要介紹了從Mybatis-Plus開始認識SerializedLambda,本文通過實例代碼給大家介紹的非常詳細,需要的朋友可以參考下2024-07-07

