地產雲:java異常和 controller的json返回對象HttpResult


 1 /**
 2  * 
 3  */
 4 package com.hikvision.building.cloud.gaia.common.exception;
 5 
 6 /**
 7  * 最基礎的異常類。
 8  * @author zhangxin13
 9  * @version 2017年11月2日下午7:20:46
10  * @since 2017年11月2日
11  */
12 abstract class AbstractException extends RuntimeException implements ExceptionInfo {
13     private static final long serialVersionUID = 3289598099629324399L;
14     private int code;
15     private String message;
16     private Object body;
17     public AbstractException(ExceptionInfo info){
18         this.code = info.getCode();
19         this.message = info.getMessage();
20         this.body = null;
21     }
22     public AbstractException(ExceptionInfo info, Object body){
23         this.code = info.getCode();
24         this.message = info.getMessage();
25         this.body = body;
26     }
27     @Override
28     public String getMessage() {
29         return message;
30     }
31     @Override
32     public int getCode() {
33         return code;
34     }
35     public Object getBody() {
36         return body;
37     }
38 }
 1 /**
 2  * 
 3  */
 4 package com.hikvision.building.cloud.gaia.common.exception;
 5 
 6 /**
 7  * 業務異常。比如輸入錯誤的數據導致業務失敗,邏輯進入到非主線分支,需要拒絕服務,讓客戶端提交正確的參數即可恢復。
 8  * 因此當遇到這種異常的時候,其實業務邏輯是執行成功的,只不過進入了非主線分支而已<br>
 9  * 當發生BusinessException時,客戶端返回的http code總是200
10  * @author zhangxin13
11  * @version 2017年11月7日上午9:40:35
12  * @since 2017年11月7日
13  */
14 public abstract class BusinessException extends AbstractException {
15     private static final long serialVersionUID = -4853537210488828688L;
16     public BusinessException(ExceptionInfo info) {
17         super(info);
18     }
19     public BusinessException(ExceptionInfo info, Object body) {
20         super(info, body);
21     }
22 }
 1 /**
 2  * 
 3  */
 4 package com.hikvision.building.cloud.gaia.common.exception;
 5 
 6 /**
 7  * 調用方異常。這類錯誤一般是servlet容器處理的,這里作為預留<br>
 8  * 當發生ClientException時,客戶端返回的http code默認400
 9  * @author zhangxin13
10  * @version 2017年11月2日下午7:19:12
11  * @since 2017年11月2日
12  */
13 public abstract class ClientException extends AbstractException {
14     private static final long serialVersionUID = 5214893309908224949L;
15     public ClientException(ExceptionInfo info) {
16         super(info);
17     }
18     public ClientException(ExceptionInfo info, Object body) {
19         super(info, body);
20     }
21 }
 1 /**
 2  * 
 3  */
 4 package com.hikvision.building.cloud.gaia.common.exception;
 5 
 6 /**
 7  * 由服務器上的邏輯漏洞或者其他什么原因導致的無法由客戶端重新提交來糾正的錯誤,
 8  * 比如服務器代碼上寫的不嚴謹在某個地方報了空指針異常,這種問題客戶端無論提交多少次正確的參數都無法修正,
 9  * 因此是屬於服務器內部錯誤。<br>
10  * 當發生ServerException時,向客戶端返回的http code為5xx。
11  * @author zhangxin13
12  * @version 2017年11月2日下午7:19:20
13  * @since 2017年11月2日
14  */
15 public abstract class ServerException extends AbstractException {
16     private static final long serialVersionUID = 3117351252348483331L;
17     public ServerException(ExceptionInfo info) {
18         super(info);
19     }
20     public ServerException(ExceptionInfo info, Object body) {
21         super(info, body);
22     }
23 }
 1 /**
 2  * 
 3  */
 4 package com.hikvision.building.cloud.gaia.common.exception;
 5 
 6 /**
 7  * 
 8  * @author zhangxin13
 9  * @version 2017年11月6日下午9:02:52
10  * @since 2017年11月6日
11  */
12 public interface ExceptionInfo {
13     public int getCode();
14     public String getMessage();
15 }
  1 /**
  2  * 
  3  */
  4 package com.hikvision.building.cloud.gaia.common.exception;
  5 
  6 import java.util.Arrays;
  7 import java.util.Map;
  8 import java.util.Map.Entry;
  9 
 10 import javax.servlet.http.HttpServletRequest;
 11 import javax.servlet.http.HttpServletResponse;
 12 
 13 import org.slf4j.Logger;
 14 import org.slf4j.LoggerFactory;
 15 import org.springframework.util.CollectionUtils;
 16 import org.springframework.web.bind.annotation.ControllerAdvice;
 17 import org.springframework.web.bind.annotation.ExceptionHandler;
 18 import org.springframework.web.bind.annotation.ResponseBody;
 19 
 20 import com.hikvision.building.cloud.gaia.common.structs.HttpResult;
 21 
 22 /**
 23  * 全局異常處理
 24  * @author zhangxin13
 25  * @version 2017年11月6日下午9:25:06
 26  * @since 2017年11月6日
 27  */
 28 @ControllerAdvice
 29 public class ExceptionHandlerAdvice {
 30     private Logger logger = LoggerFactory.getLogger(getClass());
 31 
 32     @ExceptionHandler(BusinessException.class)
 33     @ResponseBody
 34     public HttpResult<String> handlerServerException(HttpServletRequest request, HttpServletResponse response,
 35             BusinessException e){
 36         response.setStatus(200);//總是返回200
 37         response.setContentType("application/json");
 38         response.setCharacterEncoding("UTF-8");
 39         response.setHeader("Cache-Control", "no-cache");
 40         logger.info("業務異常: code: {}, message: {}", e.getCode(), e.getMessage());
 41         logger.info("URI: {}, Method: {}, Parameter: {}, DebugMessage: {}",
 42                 request.getRequestURI(), request.getMethod(), parameterMap2String(request.getParameterMap()),
 43                 e.getBody());
 44         return build(e.getCode(), e.getMessage());
 45     }
 46     @ExceptionHandler(ServerException.class)
 47     @ResponseBody
 48     public HttpResult<String> handlerServerException(HttpServletRequest request, HttpServletResponse response, 
 49             ServerException e) {
 50         if(e.getCode()<=500 || e.getCode()>599){//沒有設定 RFC 2616 規范所定義的錯誤碼,則強制設定500
 51             response.setStatus(500);
 52             logger.warn("URI: {}, Method: {} 中返回了一個不嚴謹的錯誤碼:{}",
 53                     request.getRequestURI(), request.getMethod(), e.getCode());
 54         }else{
 55             response.setStatus(e.getCode());
 56         }
 57         response.setContentType("application/json");
 58         response.setCharacterEncoding("UTF-8");
 59         response.setHeader("Cache-Control", "no-cache");
 60         logger.warn("服務端異常", e);
 61         logger.warn("URI: {}, Method: {}, Parameter: {}, DebugMessage: {}",
 62                 request.getRequestURI(), request.getMethod(), parameterMap2String(request.getParameterMap()),
 63                 e.getBody());
 64         return build(e.getCode(), e.getMessage());
 65     }
 66     
 67     @ExceptionHandler(ClientException.class)
 68     @ResponseBody
 69     public HttpResult<String> handlerClientException(HttpServletRequest request, HttpServletResponse response, 
 70             ClientException e) {
 71         if(e.getCode()<=400 || e.getCode()>499){//沒有設定 RFC 2616 規范所定義的錯誤碼,則強制設定400
 72             response.setStatus(400);
 73             logger.warn("URI: {}, Method: {} 中返回了一個不嚴謹的錯誤碼:{}",
 74                     request.getRequestURI(), request.getMethod(), e.getCode());
 75         }else{
 76             response.setStatus(e.getCode());
 77         }
 78         response.setContentType("application/json");
 79         response.setCharacterEncoding("UTF-8");
 80         response.setHeader("Cache-Control", "no-cache");
 81         logger.warn("客戶端異常", e);
 82         logger.warn("URI: {}, Method: {}, Parameter: {}, DebugMessage: {}",
 83                 request.getRequestURI(), request.getMethod(), parameterMap2String(request.getParameterMap()),
 84                 e.getBody());
 85         return build(e.getCode(), e.getMessage());
 86     }
 87     
 88     @ExceptionHandler(Exception.class)
 89     @ResponseBody
 90     public HttpResult<String> handlerException(HttpServletRequest request, HttpServletResponse response, 
 91             Exception e) {
 92         response.setStatus(500);//所有未捕獲的的異常
 93         response.setContentType("application/json");
 94         response.setCharacterEncoding("UTF-8");
 95         response.setHeader("Cache-Control", "no-cache");
 96         logger.error("發生未捕獲異常! URI: {}, Method: {}, RemoteHost: {}",
 97                 request.getRequestURI(), request.getMethod(), request.getRemoteHost());
 98         logger.error("未捕獲異常", e);
 99         return build(500, e.getMessage());
100     }
101     
102     private String parameterMap2String(Map<String, String[]> map){
103         if(CollectionUtils.isEmpty(map)){
104             return "{}";
105         }
106         StringBuilder sb = new StringBuilder("{");
107         for(Entry<String, String[]> entry: map.entrySet()){
108             sb.append(entry.getKey())
109                 .append('=')
110                 .append(Arrays.toString(entry.getValue()))
111                 .append(',');
112         }
113         sb.deleteCharAt(sb.length()-1).append('}');
114         return sb.toString();
115     }
116     
117     private HttpResult<String> build(int code,String message){
118         HttpResult<String> r = new HttpResult<>();
119         r.setCode(code);
120         r.setMessage(message);
121         return r;
122     }
123     
124 }
 1 package com.hikvision.building.cloud.gaia.common.structs;
 2 
 3 import io.swagger.annotations.ApiModel;
 4 import io.swagger.annotations.ApiModelProperty;
 5 
 6 @ApiModel
 7 public class HttpResult<T> {
 8     public static final int OK = 0;
 9     @ApiModelProperty(value="消息碼",required=true,example="0")
10     private Integer code = 0;
11     @ApiModelProperty(value="提示信息。主要用於開發調試,不建議顯示給用戶",required=true)
12     private String message;
13     @ApiModelProperty(value="返回包體",required=true)
14     private T data;
15     @ApiModelProperty(value="是否正常返回",required=true,example="true",notes="主要預留給某些不方便判斷code的場景,只要code不是0,這個字段就是false")
16     private boolean success = true;
17     
18     public HttpResult() {}
19     public HttpResult(T data) {
20         this.data = data;
21     }
22     
23     public Integer getCode() {
24         return code;
25     }
26     
27     public void setCode(Integer code) {
28         this.code = code;
29         if (code != OK) {
30             this.success = false;
31         }
32     }
33     
34     public String getMessage() {
35         return message;
36     }
37     
38     public void setMessage(String message) {
39         this.message = message;
40     }
41     
42     public T getData() {
43         return data;
44     }
45     
46     public void setData(T data) {
47         this.data = data;
48     }
49     
50     public boolean isSuccess() {
51         return this.success;
52     }
53 
54     @Override
55     public String toString() {
56         return "HttpResult [code=" + code + ", message=" + message + ", data=" + data + ", success=" + success + "]";
57     }
58     
59 }
 1 package com.hikvision.building.cloud.neptune.community.biz.exception;
 2 
 3 import com.hikvision.building.cloud.gaia.common.exception.BusinessException;
 4 import com.hikvision.building.cloud.neptune.community.biz.constant.CommunityExceptionEnum;
 5 
 6 public abstract class CommunityBusinessException extends BusinessException{
 7     private static final long serialVersionUID = 1979830642167998428L;
 8 
 9     public CommunityBusinessException(CommunityExceptionEnum info,Object object) {
10         super(info,object);
11     }
12     
13     public CommunityBusinessException(CommunityExceptionEnum info) {
14         super(info);
15     }
16 
17 }
 1 package com.hikvision.building.cloud.neptune.community.biz.exception;
 2 
 3 import com.hikvision.building.cloud.neptune.community.biz.constant.CommunityExceptionEnum;
 4 
 5 public class AreaNotExistException extends CommunityBusinessException{
 6     
 7     private static final long serialVersionUID = 6751736070431967875L;
 8 
 9     public AreaNotExistException(Object object) {
10         super(CommunityExceptionEnum.AREA_NOT_EXIST,object);
11     }
12 
13 }
  1 package com.hikvision.building.cloud.neptune.device.biz.constant;
  2 
  3 import com.hikvision.building.cloud.gaia.common.exception.ExceptionInfo;
  4 
  5 /** 
  6  * @Description 異常碼枚舉類
  7  * @author like15
  8  * @version v1.0
  9  * @date 2017年11月16日 下午1:35:02
 10  * @modificationHistory=========================邏輯或功能性重大變更記錄
 11  * @modify by user: like15 2017年11月16日
 12  * @since 2017年11月16日
 13  */
 14 public enum DeviceExceptionEnum implements ExceptionInfo{
 15     
 16     /**pageNo或者pageSize信息為空。*/
 17     DEVICE_PAGE_PARAM_EXCEPTION(960001,"pageNo或者pageSize信息不合法,必須為正整數。"),
 18     
 19     /**該社區下未配置網關信息。*/
 20     DEVICE_USERID_TOKEN_NULL(960002,"userId或者token信息為空。"),
 21     
 22     /**該社區下未配置網關信息。*/
 23     DEVICE_QUERY_TENANTID_NULL(960003,"查詢租戶id失敗。"),
 24     
 25     /**該社區下未配置網關信息。*/
 26     GATEWAY_NOT_LINK(960004,"設備網關不存在或未連接"),
 27     
 28     /**該社區下未配置網關信息。*/
 29     DEVICE_UNIT_ALREADY_EXIST(960005,"添加設備失敗,該單元已存在其他門口機設備。"),
 30     
 31     /**設備添加參數異常,devAddId、valiCode、ip、port、userName或者password為空。*/
 32     BAD_PARAMETER_DEVICE_ADD(960101,"設備添加參數異常,devAddId、ip、port、userName或者password為空。"),
 33     
 34     /**該社區下未配置網關信息。*/
 35     DEVICE_GATEWAY_NOT_EXIST(960102,"該社區下未配置網關信息。"),
 36     
 37     /**設備信息不存在或已刪除。*/
 38     DEVICE_NOT_EXIST(960103,"設備信息不存在或已刪除。"),
 39     
 40     /**設備位置信息path查詢異常。*/
 41     DEVICE_ADDRESS_PATH_EXCEPTION(960104,"設備位置信息path查詢異常。"),
 42     
 43     /**設備位置信息pathMap查詢異常。*/
 44     DEVICE_ADDRESS_PATH_MAP_EXCEPTION(960105,"設備位置信息pathMap查詢異常。"),
 45     
 46     /**該設備已被添加。*/
 47     DEVICE_ALREADY_EXIST_EXCEPTION(960106,"該設備已被添加。"),
 48     
 49     /**調用螢石協議刪除設備失敗。*/
 50     DEVICE_EZVIZ_DELETE_FAIL(960107,"調用螢石協議刪除設備失敗。"),
 51     
 52     /**設備IP或者端口不正確。*/
 53     DEVICE_IP_POER_ILLEGAL(960108,"設備IP或者端口不正確。"),
 54     
 55     /**設備用戶名或密碼不正確。*/
 56     DEVICE_USERNAME_PASSWORD_ILLEGAL(960109,"設備用戶名或密碼不正確。"),
 57     
 58     /**設備用戶名或密碼不正確。*/
 59     DEVICE_VALICODE_ILLEGAL(960110,"設備驗證碼不正確。"),
 60     
 61     /**設備位置信息path查詢異常。*/
 62     DEVICE_ADDRESS_PATH_NUMBER_EXCEPTION(960111,"設備位置信息path編號查詢異常。"),
 63     
 64     /**通行權限路徑下沒有設備信息。*/
 65     PATH_DEVICE_NOT_EXIST(960112,"通行權限路徑下沒有設備信息。"),
 66     
 67     /**卡號不能為空。*/
 68     CARD_BUMBER_NOT_EXIST(960113,"獲取卡號信息異常。"),
 69     
 70     /**調用螢石協議刪除設備失敗。*/
 71     DEVICE_DELETE_FAIL(960114,"刪除失敗。"),
 72     
 73     /**communityId為空。*/
 74     BAD_PARAMETER_DEVICE_COMMUNITYID_NULL(960201,"communityId為空。"),
 75     
 76     /**devId為空。*/
 77     BAD_PARAMETER_DEVICE_DEVSERIAL_NULL(960202,"devId為空。"),
 78     
 79     /**communityId或者tenantId為空。*/
 80     BAD_PARAMETER_DEVICE_COMMUNITYID_TENANTID_NULL(960203,"communityId或者tenantId為空。"),
 81     
 82     /**callId、callDuration或者eventTime為空。*/
 83     BAD_PARAMETER_CALL_NULL(960301,"callId、callDuration、devSerial或者eventTime為空。"),
 84     
 85     /**callId對應的呼叫記錄不存在為空。*/
 86     CALL_LOG_NOT_EXIST_EXCEPTION(960302,"callId對應的呼叫記錄不存在為空。"),
 87     ;
 88 
 89     private int code;
 90     private String message;
 91     private DeviceExceptionEnum(int code, String message) {
 92         this.code = code;
 93         this.message = message;
 94     }
 95     @Override
 96     public int getCode() {
 97         return code;
 98     }
 99 
100     @Override
101     public String getMessage() {
102         return message;
103     }
104 
105 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM