項目中才有第二種異常處理方式,我的比較推薦第二種和第三種實現方式。web
2. 使用SimpleMappingExceptionResolver實現異常處理 spring
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> mvc
<!-- 定義默認的異常處理頁面,當該異常類型的註冊時使用 --> app
<property name="defaultErrorView" value="error"></property> url
<!-- 定義異常處理頁面用來獲取異常信息的變量名,默認名爲exception --> spa
<property name="exceptionAttribute" value="ex"></property> xml
<!-- 定義須要特殊處理的異常,用類名或徹底路徑名做爲key,異常也頁名做爲值 --> 對象
<property name="exceptionMappings"> 繼承
<props> 接口
<prop key="cn.basttg.core.exception.BusinessException">error-business</prop>
<prop key="cn.basttg.core.exception.ParameterException">error-parameter</prop>
<!-- 這裏還能夠繼續擴展對不一樣異常類型的處理 -->
</props>
</property>
</bean>
3. 實現HandlerExceptionResolver 接口自定義異常處理器
public class EmvcExceptionHandler implements HandlerExceptionResolver {
private static Log log = LogFactory.getLog(EmvcExceptionHandler.class);
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception) {
String rurl = request.getServletPath();
ModelAndView model = new ModelAndView();
if (rurl.lastIndexOf(".do") > 0)
model.setViewName("/commons/error/error");
else {
model.setViewName("/error");
}
//訪問url
String url = request.getServletPath();
//訪問的參數
Enumeration enu = request.getParameterNames();
StringBuffer params = new StringBuffer();
while (enu.hasMoreElements()) {
String paraName = (String) enu.nextElement();
params.append(paraName + "=" + request.getParameter(paraName));
}
//描述信息
String message = exception.getMessage();
//異常類型
String exceptionType = exception.getClass().getName();
//異常位置
String position = null;
ByteArrayOutputStream stackTrace = new ByteArrayOutputStream();
exception.printStackTrace(new PrintStream(stackTrace));
String content = stackTrace.toString();
Pattern pat = Pattern.compile("com(.*)\\)");
Matcher mat = pat.matcher(content);
boolean rs = mat.find();
if (rs) {
position = mat.group(1);
}
position = "com"+position+")";
XaskContext.getSystemData().saveExceptionLog(Arrays.asList(new ExceptionLog(url,params.toString(),message,exceptionType,position,new Date())));
if ((exception instanceof XaskException)) {
model.addObject("errorMsg", exception.getMessage());
log.error(exception.getMessage());
return model;
}
model.addObject("errorMsg", exception.getMessage());
model.addObject("ex", exception);
log.error("未處理異常", exception);
return model;
}
}
<bean id="exceptionHandler" class="cn.basttg.core.exception.MyExceptionHandler"/>
4. 使用@ExceptionHandler註解實現異常處理
@ExceptionHandler
public String exp(HttpServletRequest request, Exception ex) {
System.out.println("異常捕捉||||||"+ex.getClass() + " ||||||====== " +ex.getMessage());
request.setAttribute("ex", ex);
// 根據不一樣錯誤轉向不一樣頁面
if (ex instanceof ParameterException) {
return "error-parameter";
} else {
return "error";
}
}