首頁 > 軟體

Spring Boot統一介面返回及全域性例外處理

2022-04-20 22:00:10

前言:

前段時間接手了一個老專案,現在需要在此專案中新增一些新的需求,同事在開發過程中遇到了一些問題?

  • 1.成功的狀態到底是200還是0啊,訂單系統200代表成功,而會員系統卻是0代表成功。
  • 2.介面返回的結果中,有些是用msg欄位表示描述,有些又是用desc欄位描述,前段處理起來比較麻煩能不能統一。
  • 3.錯誤提示資訊需要支援國際化。

其實這些問題,歸根究底還是程式碼規範問題,我們需要將介面定義和全域性異常統一處理,歷史專案10多個工程,難道每個工程都去實現一遍,答案可定是不可能的。

1、解決方案

定義公共模組,實現統一介面定義規範和例外處理,其他的系統進行依賴和擴充套件即可。

2、具體實現

2.1 定義狀態碼統一介面

public interface BaseResultCode
{
    /**
     * 狀態碼
     * @return
     */
    int getCode();
    /**
     * 提示資訊
     * @return
     */
    String getMsg();
}

2.2 公共模組狀態碼列舉類

public enum ResultCode implements BaseResultCode
{
    OK(200, "成功"),
    ERROR(300,"系統異常"), 
    NEED_AUTH(301, "非法請求,請重新登入"), 
    PARAMTER_ERROR(302, "引數錯誤");
    //省略其他定義錯誤碼
    private int code;
    private String msg;
    private ResultCode(int code, String msg)
    {
        this.code = code;
        this.msg = msg;
    }
    public static ResultCode getValue(int code)
    {
        for (ResultCode errorCode : values())
        {
            if (errorCode.getCode() == code)
            {
                return errorCode;
            }
        }
        return null;
    }
   //省略Get、Set方法
 }

2.3 定義全域性自定義異常

public class SysException extends RuntimeException
{
    private static final long serialVersionUID = 5225171867523879342L;
    private int code;
    private String msg;
    private Object[] params;
    private BaseResultCode errorCode;
    public SysException()
    {
        super();
    }
    public SysException(String message)
    {
        super(message);
    }
    public SysException(Throwable cause)
    {
        super(cause);
    }
    public SysException(int code ,String message)
    {
        this.code = code;
        this.msg = message;
    }
    public SysException(int code ,String message,  Object[] params)
    {
        this(code, message);
        this.params= params;
    }
    public SysException(String message, Throwable cause)
    {
        super(message, cause);
    }
    public SysException(BaseResultCode errorCode)
    {
        this.errorCode = errorCode;
    }
    public SysException(String message, Object[] params)
    {
        super(message);
        this.params = params;
    }
    public SysException(BaseResultCode errorCode, String message, Object[] params)
    {
        this(message, params);
        this.errorCode = errorCode;
    }
    
    /**
     * Construct by default
     * 
     * @param message
     *            message
     * @param parameters
     *            parameters
     * @param cause
     *            cause
     */
    public SysException(String message, Object[] params, Throwable cause)
    {
        super(message, cause);
        this.params = params;
    }

    public int getCode()
    {
        return code;
    }
    public void setCode(int code)
    {
        this.code = code;
    }
    public String getMsg()
    {
        return msg;
    }
    public void setMsg(String msg)
    {
        this.msg = msg;
    }
    /**
     * @return the params
     */
    public Object[] getParams()
    {
        return params;
    }
    /**
     * @param params
     *            the params to set
     */
    public void setParams(Object[] params)
    {
        this.params = params;
    }
    public BaseResultCode getErrorCode()
    {
        return errorCode;
    }
    public void setErrorCode(BaseResultCode errorCode)
    {
        this.errorCode = errorCode;
    }
    
}

2.4 定義統一介面格式輸出類

public class Result implements Serializable
{
    private static final long serialVersionUID = -1773941471021475043L;
    private Object data;
    private int code;
    private String msg;
    public Result()
    {
    }
    public Result(int code, Object data, String msg)
    {
        this.code = code;
        this.data = data;
        this.msg = msg;
    }
    public Result(int code, String desc)
    {
        this(code, null, desc);
    }
    public Result(BaseResultCode errorCode)
    {
        this(errorCode.getCode(), null, errorCode.getMsg());
    }
    public static Result success()
    {
        return success(null);
    }
    public static Result success(Object data)
    {
        Result result = new Result();
        result.setData(data);
        result.setCode(ResultCode.OK.getCode());
        return result;
    }
    public static Result error(String msg)
    {
        Result result = new Result();
        result.setCode(ResultCode.ERROR.getCode());
        result.setMsg(msg);
        return result;
    }
    public static Result error(BaseResultCode baseCode)
    {
        Result result = new Result();
        result.setCode(baseCode.getCode());
        result.setMsg(baseCode.getMsg());
        return result;
    }
}

個人建議:統一介面輸出類不要定義為泛型型別

2.5 定義統一介面格式輸出類

@RestControllerAdvice
public class SysExceptionHandler
{
    public static Log logger = LogManager.getLogger(SysExceptionHandler.class);
    @ExceptionHandler(Exception.class)
    public Result handleException(HttpServletRequest request,
            Exception ex)
    {
        logger.error("Handle Exception Request Url:{},Exception:{}",request.getRequestURL(),ex);
        Result result = new Result();
        //系統異常
        if (ex instanceof SysException)
        {
            SysException se = (SysException) ex;
            BaseResultCode resultCode =se.getErrorCode();
            if(resultCode==null)
            {
                result = Result.error(se.getMessage());
            }
            else
            {
               result = new Result(resultCode.getCode(),
                                       StringUtil.isNotEmpty(se.getMessage())?se.getMessage():resultCode.getMsg());
            }
        }
        //引數錯誤
        else if (ex instanceof ConstraintViolationException)
        {
            ConstraintViolationException v = (ConstraintViolationException) ex;
            String message = v.getConstraintViolations().iterator().next()
                    .getMessage();
            result.setCode(ResultCode.PARAMTER_ERROR.getCode());
            result.setMsg(ResultCode.PARAMTER_ERROR.getMsg() + ":" + message);
        }
        //引數錯誤
        else if (ex instanceof BindException)
        {
            BindException v = (BindException) ex;
            String message = v.getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(","));
            result.setCode(ResultCode.PARAMTER_ERROR.getCode());
            result.setMsg(ResultCode.PARAMTER_ERROR.getMsg() + ":" + message);
        }
        //引數錯誤
        else if (ex instanceof MethodArgumentNotValidException)
        {
            MethodArgumentNotValidException v = (MethodArgumentNotValidException) ex;
            String message = v.getBindingResult().getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(","));
            result.setCode(ResultCode.PARAMTER_ERROR.getCode());
            result.setMsg(ResultCode.PARAMTER_ERROR.getMsg() + ":" + message);
        }
        else
        {
           result = new Result(ResultCode.ERROR.getCode(),ExceptionUtil.getErrorMsg(ex));
        }
        logger.info("exception handle reuslt:" + result);
        return result;
    }
}

上述定義已經可以實現全域性介面和異常的統一處理,但是存在的如下問題

每個controller都需要返回Reesult型別,且每個方法都需要返回Result.success()或者Result.success(data)的結果,有點重複,需要進行優化。

    @GetMapping("addUser")
    public Result add()
    {
       for(int i=0;i<10;i++)
       {
           TUser user = new TUser();
           //user.setOid(IdWorker.getId());
           user.setName("shareing_"+i);
           user.setAge(i);
           userService.addUser(user);
       }
       return Result.success();
    }

2.6 介面統一輸出優化

實現方式只需要實現ResponseBodyAdvice介面,重寫beforeBodyWrite方法介面。

@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object>
{
    private Logger logger = LoggerFactory.getLogger(ResponseAdvice.class);
    @Override
    public boolean supports(MethodParameter returnType,
            Class<? extends HttpMessageConverter<?>> converterType)
    {
        return true;
    }
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter returnType,
            MediaType selectedContentType,
            Class<? extends HttpMessageConverter<?>> selectedConverterType,
            ServerHttpRequest request, ServerHttpResponse response)
    {
        logger.info("before body write param:{}",o);
        if(o instanceof String)
        {
           //序列化結果輸出
           return FastJsonUtil.toJSONString(Result.success(o));
        }
        else if (o instanceof Result)
        {
             return o;
        }
        return Result.success(o);
    }
}

經過優化後,controller輸出可以根據業務的需求定義輸出物件。

 @GetMapping("getUserByName")
    public TUser getUserByName1(@RequestParam String name)
    {
       logger.info("getUserByName paramter name:"+name);
       return userService.getUserByName(name); 
    }

2.7 子系統如何實現

子系統引入common的jar包,

  <dependency>
	    <groupId>com.xx</groupId>
	    <artifactId>xx-common</artifactId>
	    <version>2.0</version>
	</dependency>

3、子系統定義狀態碼,實現BaseResultCode介面

 public enum OrderModelErrorCode implements BaseResultCode
{
    ORDER_STATUS_ERROR(1000, "訂單狀態不正確");
    private int code;
    private String msg;
    private UserModelErrorCode(int code, String msg)
    {
        this.code = code;
        this.msg = msg;
    }
    @Override
    public int getCode()
    {
        return code;
    }
    @Override
    public String getMsg()
    {
        return msg;
    }
}

定義例外處理類,繼承公共例外處理類SysExceptionHandler

@RestControllerAdvice
public class OrderModalExceptionHandle extends SysExceptionHandler
{
     @Override
    public Result handleException(HttpServletRequest request, Exception ex)
    {
        return super.handleException(request, ex);
        //子系統可以擴充套件例外處理
    }
}

子系統使用範例:

@Override
public Order getOrder(String orderId)
{
	Order order =getOrder(orderId);
        //相關虛擬碼
	if(order.getStatus()>120)
	{
	   throw new SysException(OrderModelErrorCode.ORDER_STATUS_ERROR);    
	}
	return order;
}

經過相關專案的重構,已經解決了第一個和第二問題,關於第三個國際化問題,將在後續的文章中講解。

到此這篇關於Spring Boot統一介面返回以及全域性例外處理的文章就介紹到這了,更多相關Spring Boot例外處理內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com