Spring MVC處理異常有3種方式java
(1)實現Spring的異常處理接口HandlerExceptionResolver 自定義本身的異常處理器web
1.建立本身的異常處理spring
public class MyExceptionHandler implements HandlerExceptionResolver { app
if(ex instanceof BusinessException) { jsp
return new ModelAndView("error-business", model); spa
}else if(ex instanceof ParameterException) { 日誌
return new ModelAndView("error-parameter", model); code
} else { xml
return new ModelAndView("error", model); 接口
}
}
2.添加到容器中,servletDespatcher
<bean id="exceptionHandler" class="cn.basttg.core.exception.MyExceptionHandler"/>
(2)使用@ExceptionHandler註解實現異常處理
1.1
public class BaseController {
/** 基於@ExceptionHandler異常處理 */
@ExceptionHandler
public String exp(HttpServletRequest request, Exception ex) {
request.setAttribute("ex", ex);
// 根據不一樣錯誤轉向不一樣頁面
if(ex instanceof BusinessException) {
return "error-business";
}else if(ex instanceof ParameterException) {
return "error-parameter";
} else {
return "error";
}
}
}
1.2
@ExceptionHandler({MyException.class})
public String exception(MyException e) {
System.out.println(e.getMessage());
e.printStackTrace();
return "exception";
}
2.
public class TestController extends BaseController
(3)使用Spring MVC提供的簡單異常處理器SimpleMappingExceptionResolve
1.
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!-- 定義默認的異常處理頁面,當該異常類型的註冊時使用 -->
<property name="defaultErrorView" value="error"></property>
<!-- 定義異常處理頁面用來獲取異常信息的變量名,默認名爲exception -->
<property name="exceptionAttribute" value="ex"></property>
<!-- 定義須要特殊處理的異常,用類名或徹底路徑名做爲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>
2.
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.Exception">errors/error</prop>
<prop key="java.lang.Throwable">errors/err</prop>
</props>
</property>
<property name="statusCodes">
<props>
<prop key="errors/error">500</prop>
<prop key="errors/404">404</prop>
</props>
</property>
<!-- 設置日誌輸出級別,不定義則默認不輸出警告等錯誤日誌信息 -->
<property name="warnLogCategory" value="WARN"></property>
<!-- 默認錯誤頁面,當找不到上面mappings中指定的異常對應視圖時,使用本默認配置 -->
<property name="defaultErrorView" value="errors/error"></property>
<!-- 默認HTTP狀態碼 -->
<property name="defaultStatusCode" value="500"></property>
</bean>
最後在web.xml中定義
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/500.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/500.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/404.jsp</location>
</error-page>