springboot項目統一封裝返回值和異常處理(方式一)


為什么要統一返回值:

在我們做后端應用的時候,前后端分離的情況下,我們經常會定義一個數據格式,通常會包含codemessagedata這三個必不可少的信息來方便我們的交流,下面我們直接來看代碼package com.house.common;

import java.util.Properties;
import lombok.Data;

/**
 * 統一定義返回類
 *
 */
@Data
public class ReturnVO {

    //獲取程序當前路徑下的文件
    private static final Properties properties = ReadPropertiesUtil
        .getProperties(System.getProperty("user.dir") + "/src/main/resources/response.properties");

    /**
     * 返回代碼
     */
    private String code;

    /**
     * 返回信息
     */
    private String message;

    /**
     * 返回數據
     */
    private Object data;

/** * 默認構造,返回操作正確的返回代碼和信息 */ 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); } @Override public String toString() { return "ReturnVO{" + "code='" + code + '\'' + ", message='" + message + '\'' + ", data=" + data + '}'; } }

在這里,我提供了幾個構造方法以供不同情況下使用。代碼的注釋已經寫得很清楚了,大家也可以應該看的比較清楚~

ReturnCode

細心的同學可能發現了,我單獨定義了一個ReturnCode枚舉類用於存儲代碼和返回的Message:

package com.house.common;

public enum ReturnCode {

    /** 操作成功 */
    SUCCESS("SUCCESS_CODE", "SUCCESS_MSG"),

    /** 操作失敗 */
    FAIL("FAIL_CODE", "FAIL_MSG"),

    /** 空指針異常 */
    NullpointerException("NPE_CODE", "NPE_MSG"),

    /** 自定義異常之返回值為空 */
    NullPointerException("NRE_CODE", "NRE_MSG");


    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;
}

這里,我並沒有將需要存儲的數據直接放到枚舉中,而是放到了一個配置文件中response.properties,這樣既可以方便我們進行相關信息的修改,並且閱讀起來也是比較方便。

注意,這里的屬性名和屬性值分別與枚舉類中的value和msg相對應,這樣,我們才可以方便的去通過I/O流去讀取。

SUCCESS_CODE = 1000
SUCCESS_MSG = success
NRE_CODE = 1021
NRE_MSG = exception001

(如不定義中文字段則跳過這步驟)  這里需要注意一點,如果你使用的是IDEA編輯器,需要修改以下的配置,這樣你編輯配置文件的時候寫的是中文,實際上保存的是ASCII字節碼。

 下面,來看一下讀取的工具類:

package com.house.common;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

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;
    }
}

測試使用ReturnVO返回定義的格式:

@RequestMapping("/test")
public ReturnVO test(){
   try {
        //省略
        //省略
    }  catch (Exception e) {
            e.printStackTrace();
   }
     return new ReturnVO();
}

下面我們可以去訪問這個接口,看看會得到什么:

 

 但是,現在問題又來了,因為try...catch...的存在,總是會讓代碼變得重復度很高,一個接口你都至少要去花三到十秒去寫這個接口,如果不知道編輯器的快捷鍵,更是一種噩夢。

我們只想全心全意的去關注實現業務,而不是花費大量的時間在編寫一些重復的"剛需"代碼上。

使用AOP進行全局異常的處理

(這里,我只是對全局異常處理進行一個簡單的講解,后面也就是下一節中會詳細的講述):

package com.house.common;

import java.util.Properties;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 統一封裝返回值和異常處理
 *
 */
@Slf4j
@Aspect
@Order(5)
@Component
public class ResponseAop {

    //獲取程序當前路徑下的文件
    private static final Properties properties = ReadPropertiesUtil.getProperties(System.getProperty("user.dir")
        + "/src/main/resources/response.properties");

     // 切點(在包下的所有controller以及他的子包)
    //@Pointcut("execution(public * com.house.controller.*.controller..*(..))")
    @Pointcut("execution(public * com.house.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;
    }
}
      <!--在使用切面注解@Aspect-->
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
        <scope>test</scope>
      </dependency>

      <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
      </dependency>

下面我們來測試一下,訪問我們經過修改后的編寫的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();
    }

下一篇,用springboot自帶的注解@ControllerAdvice 實現統一異常處理。

 


免責聲明!

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



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