目錄
- 為什么要統一返回值
- ReturnVO
- ReturnCode
- 使用ReturnVO
- 使用AOP進行全局異常的處理
- 云擼貓
- 公眾號
為什么要統一返回值
在我們做后端應用的時候,前后端分離的情況下,我們經常會定義一個數據格式,通常會包含code
,message
,data
這三個必不可少的信息來方便我們的交流,下面我們直接來看代碼
ReturnVO
package indi.viyoung.viboot.util;import java.util.Properties;/*** 統一定義返回類** @author yangwei* @since 2018/12/20*/
public class ReturnVO {private static final Properties properties = ReadPropertiesUtil.getProperties(System.getProperty("user.dir") + "/viboot-common/src/main/resources/response.properties");/*** 返回代碼*/private String code;/*** 返回信息*/private String message;/*** 返回數據*/private Object data;public Object getData() {return data;}public void setData(Object data) {this.data = data;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}public String getCode() {return code;}public void setCode(String code) {this.code = code;}/*** 默認構造,返回操作正確的返回代碼和信息*/public ReturnVO() {this.setCode(properties.getProperty(ReturnCode.SUCCESS.val()));this.setMessage(properties.getProperty(ReturnCode.SUCCESS.msg()));}/*** 構造一個返回特定代碼的ReturnVO對象* @param code*/public ReturnVO(ReturnCode code) {this.setCode(properties.getProperty(code.val()));this.setMessage(properties.getProperty(code.msg()));}/*** 默認值返回,默認返回正確的code和message* @param data*/public ReturnVO(Object data) {this.setCode(properties.getProperty(ReturnCode.SUCCESS.val()));this.setMessage(properties.getProperty(ReturnCode.SUCCESS.msg()));this.setData(data);}/*** 構造返回代碼,以及自定義的錯誤信息* @param code* @param message*/public ReturnVO(ReturnCode code, String message) {this.setCode(properties.getProperty(code.val()));this.setMessage(message);}/*** 構造自定義的code,message,以及data* @param code* @param message* @param data*/public ReturnVO(ReturnCode code, String message, Object data) {this.setCode(code.val());this.setMessage(message);this.setData(data);}@Overridepublic String toString() {return "ReturnVO{" +"code='" + code + '\'' +", message='" + message + '\'' +", data=" + data +'}';}
}
在這里,我提供了幾個構造方法以供不同情況下使用。代碼的注釋已經寫得很清楚了,大家也可以應該看的比較清楚~
ReturnCode
細心的同學可能發現了,我單獨定義了一個ReturnCode
枚舉類用于存儲代碼和返回的Message:
package indi.viyoung.viboot.util;/*** @author yangwei* @since 2018/12/20*/
public enum ReturnCode {/** 操作成功 */SUCCESS("SUCCESS_CODE", "SUCCESS_MSG"),/** 操作失敗 */FAIL("FAIL_CODE", "FAIL_MSG"),/** 空指針異常 */NullpointerException("NPE_CODE", "NPE_MSG"),/** 自定義異常之返回值為空 */NullResponseException("NRE_CODE", "NRE_MSG");private ReturnCode(String value, String msg){this.val = value;this.msg = msg;}public String val() {return val;}public String msg() {return msg;}private String val;private String msg;
}
這里,我并沒有將需要存儲的數據直接放到枚舉中,而是放到了一個配置文件中,這樣既可以方便我們進行相關信息的修改,并且閱讀起來也是比較方便。
SUCCESS_CODE=2000
SUCCESS_MSG=操作成功FAIL_CODE=5000
FAIL_MSG=操作失敗NPE_CODE=5001
NPE_MSG=空指針異常NRE_CODE=5002
NRE_MSG=返回值為空
注意,這里的屬性名和屬性值分別與枚舉類中的value和msg相對應,這樣,我們才可以方便的去通過I/O流去讀取。
這里需要注意一點,如果你使用的是IDEA編輯器,需要修改以下的配置,這樣你編輯配置文件的時候寫的是中文,實際上保存的是ASCII字節碼。
下面,來看一下讀取的工具類:
package indi.viyoung.viboot.util;import java.io.*;
import java.util.Iterator;
import java.util.Properties;/*** 讀取*.properties中的屬性* @author vi* @since 2018/12/24 7:33 PM*/
public class ReadPropertiesUtil {public static Properties getProperties(String propertiesPath){Properties properties = new Properties();try {InputStream inputStream = new BufferedInputStream(new FileInputStream(propertiesPath));properties.load(inputStream);} catch (IOException e) {e.printStackTrace();}return properties;}
}
這里我直接寫了一個靜態的方法,傳入的參數是properties文件的位置,這樣的話,本文最初代碼中的也就得到了解釋。
private static final Properties properties = ReadPropertiesUtil.getProperties(System.getProperty("user.dir") + "/viboot-common/src/main/resources/response.properties");
使用ReturnVO
@RequestMapping("/test")public ReturnVO test(){try {//省略//省略} catch (Exception e) {e.printStackTrace();}return new ReturnVO();}
下面我們可以去訪問這個接口,看看會得到什么:
但是,現在問題又來了,因為try...catch...
的存在,總是會讓代碼變得重復度很高,一個接口你都至少要去花三到十秒去寫這個接口,如果不知道編輯器的快捷鍵,更是一種噩夢。我們只想全心全意的去關注實現業務,而不是花費大量的時間在編寫一些重復的"剛需"代碼上。
使用AOP進行全局異常的處理
(這里,我只是對全局異常處理進行一個簡單的講解,后面也就是下一節中會詳細的講述)
/*** 統一封裝返回值和異常處理** @author vi* @since 2018/12/20 6:09 AM*/
@Slf4j
@Aspect
@Order(5)
@Component
public class ResponseAop {private static final Properties properties = ReadPropertiesUtil.getProperties(System.getProperty("user.dir") + "/viboot-common/src/main/resources/response.properties");/*** 切點*/@Pointcut("execution(public * indi.viyoung.viboot.*.controller..*(..))")public void httpResponse() {}/*** 環切*/@Around("httpResponse()")public ReturnVO handlerController(ProceedingJoinPoint proceedingJoinPoint) {ReturnVO returnVO = new ReturnVO();try {//獲取方法的執行結果Object proceed = proceedingJoinPoint.proceed();//如果方法的執行結果是ReturnVO,則將該對象直接返回if (proceed instanceof ReturnVO) {returnVO = (ReturnVO) proceed;} else {//否則,就要封裝到ReturnVO的data中returnVO.setData(proceed);}} catch (Throwable throwable) {//如果出現了異常,調用異常處理方法將錯誤信息封裝到ReturnVO中并返回returnVO = handlerException(throwable);}return returnVO;}/*** 異常處理*/ private ReturnVO handlerException(Throwable throwable) {ReturnVO returnVO = new ReturnVO();//這里需要注意,返回枚舉類中的枚舉在寫的時候應該和異常的名稱相對應,以便動態的獲取異常代碼和異常信息//獲取異常名稱的方法String errorName = throwable.toString();errorName = errorName.substring(errorName.lastIndexOf(".") + 1);//直接獲取properties文件中的內容returnVO.setMessage(properties.getProperty(ReturnCode.valueOf(errorName).msg()));returnVO.setCode(properties.getProperty(ReturnCode.valueOf(errorName).val()));return returnVO;}
}
如果,我們需要在每一個項目中都可以這么去做,需要將這個類放到一個公用的模塊中,然后在pom中導入這個模塊
<dependency><groupId>indi.viyoung.course</groupId><artifactId>viboot-common</artifactId><version>1.0-SNAPSHOT</version></dependency>
這里需要注意一點,必須保證你的切點的正確書寫!!否則就會導致切點無效,同時需要在啟動類中配置:
@ComponentScan(value = "indi.viyoung.viboot.*")
導入的正是common
包下的所有文件,以保證可以將ResponseAop
這個類加載到Spring的容器中。
下面我們來測試一下,訪問我們經過修改后的編寫的findAll
接口:
@RequestMapping("/findAll")public Object findAll(){return userService.list();}
PS:這里我將返回值統一為Object,以便數據存入data
,實際類型應是Service
接口的返回類型。如果沒有返回值的話,那就可以new
一個ReturnVO
對象直接通過構造方法賦值即可。關于返回類型為ReturnVO
的判斷,代碼中也已經做了特殊的處理,并非存入data
,而是直接返回。
下面,我們修改一下test方法,讓他拋出一個我們自定義的查詢返回值為空的異常:
@RequestMapping("/test")public ReturnVO test(){throw new NullResponseException();}
下面,我們再來訪問以下test接口:
可以看到,正如我們properties中定義的那樣,我們得到了我們想要的消息。
原創文章,文筆有限,才疏學淺,文中若有不正之處,萬望告知。
源碼可以去github或者碼云上進行下載,后續的例子都會同步更新。
云擼貓
公眾號
如果幫到了你,請點擊推薦讓更多人看到~