而像IOException這類跟外在環境有關的異常,幾乎是不可避免的(指不定哪一天哪一秒網絡就掛了),但是當不期而遇時,程序還是要有所作為,所以編譯器有必要督促一下程序員,Check一下,看看是否對這些可能不期而至的異常進行了處理。當Exception對象傳遞到某個節點后,程序就可以執行一些措施了,比如:給用戶返回一個提示("系統繁忙,請重試"),給監控平臺推送一個異常消息等等。
二、異常的統一返回處理1、服務器處理下面列舉Tomcat和Nginx為例Tomcat是Servlet容器,主要處理動態請求,在web.xml下配置,按http返回碼或Exception類型來處理:
<error-page> <error-code>404</error-code> <location>/WEB-INF/views/error/404.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/WEB-INF/views/error/500.jsp</location> </error-page> <error-page> <exception-type>java.lang.Throwable</exception-type> <location>/WEB-INF/views/error/throwable.jsp</location> </error-page>Nginx是反向代理服務器,通過Http返回碼也可以很方便地指定異常時的返回頁面:server { listen 80 ; server_name xx.com ; root /var/www ; index index.html ; error_page 404 /404.html ; location = /404.html { root /usr/share/nginx/html; } } 2、框架處理下面列舉SPRing MVC的處理方式(1)使用Spring MVC自帶的簡單異常處理器SimpleMappingExceptionResolver; (2)實現接口HandlerExceptionResolver 自定義異常處理器; (建議使用,可支持Ajax等擴展)(3)使用@ExceptionHandler注解實現異常處理; 第(1)種,在spring-mvc.xml下配置<!-- 將Controller拋出的異常轉到特定視圖 --> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <!-- 不同異常分開跳轉--> <!-- 可以自定義不同的異常--> <prop key="com.test.MyException1">/error/e1</prop> <prop key="com.test.MyException2">/error/e2</prop> <!-- 如果不想自定義異常,只配置下面的即可--> <prop key="java.lang.Throwable">/error/500</prop> </props> </property> </bean>缺點:無法處理不需要返回html的請求;第(2)種,自定義HandlerExceptionResolver接口的實現類
/** * 自定義異常處理器:支持ajax * */public class MyExceptionHandler implements HandlerExceptionResolver { public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { /* 區分ajax */ boolean isAjax = request.getHeader("X-Requested-With") != null && "xmlhttpRequest".equals(request .getHeader("X-Requested-With").toString()); if (!isAjax) { if (ex instanceof com.test.MyException1) { return new ModelAndView("/error/e1"); } else if (ex instanceof com.test.MyException1) { return new ModelAndView("/error/e2"); } else { return new ModelAndView("/error/500"); } } String jsonRes = "{/"message/":/"" + "系統異常" + "/"}";// 自定義結構和前臺對接 PrintWriter out = null; try { response.setCharacterEncoding("utf-8"); response.setContentType("application/json;charset=UTF-8"); out = response.getWriter(); out.print(jsonRes); out.flush(); } catch (IOException e) { e.printStackTrace(); } finally { out.close(); } return null; }}并在spring-mvc.xml下注冊處理器<bean id="exceptionHandler" class="com.test.MyExceptionHandler"/>優點:可以處理ajax請求,也方便編碼實現功能擴展,比如異常的監控等。第(3)種,@ExceptionHandler注解@Controllerpublic class TestExceptionHandlerController { @ExceptionHandler({ MyException1.class }) public String exception(MyException1 e) { return "/error/e1"; } @RequestMapping("/marry") public void test() { throw new MyException1("有問題"); }}缺點:@ExceptionHandler的方法,必須和可能拋異常的方法在一同個Controller下。(不建議使用)PS:實際情況,會將返回碼的映射交給服務器,將動態請求的一些自定義異常或者功能擴展交給框架。
新聞熱點
疑難解答