程序中对异常情况的处理

目前开发的一个项目

开发一个新功能,总是感觉很吃力,

因为总是要处理各种协作方接口异常情况:

(a)502 服务器没有启动

(b)403 拒绝访问

(c)404 接口路径不对

(d)500 服务器内部错误

 

如果把这些错误信息一层层往上返回,会非常麻烦

在业务逻辑中参杂了这些与业务一点关系都没有的代码,看起来很累赘.

看下面的代码:


程序中对异常情况的处理
 
程序中对异常情况的处理
 
程序中对异常情况的处理
 

错误是一步步往上传递,每一个方法里面都在处理,感觉好累

最下面的代码片段是控制器里面的,

在其他控制器里面也会看到类似的代码

其实可以统一处理的

这些异常应该在一个地方统一捕获,统一处理.

而不是东处理一个,西处理一个,看起来很乱,容易造成冗余和重复,很难维护.

下面我就漏改了:


程序中对异常情况的处理
 程序中对异常情况的处理

 

 

如何实现异常统一处理呢?

第一,遇到异常直接抛出,而不是马上处理;

第二,一个异常handler进行统一处理

handler 类:

Java代码  程序中对异常情况的处理
  1. package com.chanjet.gov.handler;  
  2.   
  3. import com.chanjet.gov.bean.exception.MustBeDealedException;  
  4. import com.chanjet.gov.util.Constant;  
  5. import org.springframework.web.bind.annotation.ControllerAdvice;  
  6. import org.springframework.web.bind.annotation.ExceptionHandler;  
  7. import org.springframework.web.context.request.RequestContextHolder;  
  8. import org.springframework.web.context.request.ServletRequestAttributes;  
  9.   
  10. import javax.servlet.http.HttpServletResponse;  
  11. import java.io.IOException;  
  12.   
  13. /** 
  14.  * Created by whuanghkl on 3/30/16. 
  15.  */  
  16. //注意使用注解@ControllerAdvice作用域是全局Controller范围  
  17. //可应用到所有@RequestMapping类或方法上的@ExceptionHandler、@InitBinder、@ModelAttribute,在这里是@ExceptionHandler  
  18. @ControllerAdvice  
  19. public class ExceptionHandlerAdvice {  
  20.     @ExceptionHandler(MustBeDealedException.class)  
  21. //    @RESPONSE_CONTENTTYPE_JSON_UTFStatus(HttpStatus.BAD_REQUEST)  
  22. //    @ResponseBody  
  23.     public String handleIOException(MustBeDealedException ex) {  
  24. //        return ClassUtils.getShortName(ex.getClass()) + ex.getMessage();  
  25.          
  26.         System.out.println(ex);  
  27.         HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();  
  28.         String responseStatusCode = ex.getResponseStatusCode();  
  29.         if (null == responseStatusCode) {  
  30.             responseStatusCode = Constant.EMPTY;  
  31.         }  
  32.         try {  
  33.             response.sendRedirect("/error.html?error=" + ex.getErrorCode() + "&responseStatusCode=" + responseStatusCode);  
  34.         } catch (IOException e) {  
  35.             e.printStackTrace();  
  36.         }  
  37.         return null;  
  38.     }  
  39. }  

 

参考:http://www.cnblogs.com/xguo/p/3163519.html