springmvc 自定義異常處理
阿新 • • 發佈:2019-01-23
springmvc利用HandlerExceptionResolver處理程式的異常,包括處理對映對映異常,資料繫結,處理器執行過程中發生的異常
public interface HandlerExceptionResolver {
ModelAndView resolveException(
HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex);
}
當發生異常的時候,直接呼叫resolveException,生成一個modelandview報告給使用者
HandlerExceptionResolver 的實現類預設有四個
1.DefaultHandlerExceptionResolver 預設已經安裝,他會直接將異常轉化成相應的響應狀態碼,可以在web.xml配置狀態,轉到響應的異常處理頁面
<error-page>
<error-code>403</error-code>
<location>/WEB-INF/jsp/error/403.jsp</location>
</error-page>
<error-page>
<error-code >404</error-code>
<location>/WEB-INF/jsp/error/404.jsp</location>
</error-page>
<error-page>
<error-code>405</error-code>
<location>/WEB-INF/jsp/error/405.jsp</location>
</error-page>
<error-page>
<error-code >500</error-code>
<location>/WEB-INF/jsp/error/500.jsp</location>
</error-page>
2.AnnotationMethodHandlerExceptionResolver 預設已經安裝,可以通過註解的方式處理異常
@ExceptionHandler(RuntimeException.class)
@ResponseBody
public String handlerException(){
return "task/error";
}
@ExceptionHandler可以指定監聽哪個異常型別,如果不指定,則預設不監聽任何異常
3.SimpleMappingExceptionResolver 可以對異常統一處理,然後既愛那個異常類異常為檢視名,發生錯誤時,可以把異常報告給使用者,我們可以利用它來自定義異常處理。
public class CustomerExceptionHandler extends SimpleMappingExceptionResolver {
@Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception exception) {
String viewName = determineViewName(exception, request);
if (viewName != null) {
if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request
.getHeader("X-Requested-With")!= null && request
.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {//非非同步請求
Integer statusCode = determineStatusCode(request, viewName);
if (statusCode != null) {
applyStatusCodeIfPossible(request, response, statusCode);
}
return getModelAndView(viewName, exception, request);
} else {//非同步請求的話,發生異常則直接把異常寫到輸出流中,將ModelAndView置為空,則springmvc不處理response
try {
PrintWriter print = response.getWriter();
print.write(exception.getMessage());
print.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
} else {
return null;
}
}
}
我們這裡自定義了一個異常處理器,可以處理非同步請求發生的異常,然後我們把自定義的異常處理註冊到springmvc中
<bean class="com.liuxg.util.exception.CustomerExceptionHandler">
<property name="exceptionMappings">
<props>
<prop key="com.liuxg.util.exception.SystemException">task/task</prop>
</props>
</property>
</bean>
這裡我們還可以自定義一些異常對映處理類,例如,我們自己定義SystemException異常處理類
@SuppressWarnings("serial")
public class SystemException extends Exception {
public SystemException(String msg) {
super(msg);
}
public SystemException(Throwable cause) {
super(cause);
}
public SystemException(String msg, Throwable cause) {
super(msg, cause);
}
}
然後我們在程式中就可以丟擲自己定義的異常類別,然後交由我們自定義的處理器進行處理
@RequestMapping("/mvcTest1")
public void mvcTest1() throws SystemException{
throw new SystemException("系統異常");
}