微服务中统一返回状态码

1.封装统一返回对象

@Data public class BaseResponse { private Integer rtnCode; private String msg; private T data; public BaseResponse() { } public BaseResponse(Integer rtnCode, String msg, T data) { super(); this.rtnCode = rtnCode; this.msg = msg; this.data = https://www.it610.com/article/data; }}

2.常量
public interface Constants { // 响应请求成功 String HTTP_RES_CODE_200_VALUE = "https://www.it610.com/article/success"; // 系统错误 String HTTP_RES_CODE_500_VALUE = "https://www.it610.com/article/fial"; // 响应请求成功code Integer HTTP_RES_CODE_200 = 200; // 系统错误 Integer HTTP_RES_CODE_500 = 500; }

3.封装业务类需要继承的父类
@Data @Component public class BaseApiService { public BaseResponse setResultError(Integer code, String msg) { return setResult(code, msg, null); } // 返回错误,可以传msg public BaseResponse setResultError(String msg) { return setResult(Constants.HTTP_RES_CODE_500, msg, null); } // 返回成功,可以传data值 public BaseResponse setResultSuccess(Object data) { return setResult(Constants.HTTP_RES_CODE_200, Constants.HTTP_RES_CODE_200_VALUE, data); } // 返回成功,沒有data值 public BaseResponse setResultSuccess() { return setResult(Constants.HTTP_RES_CODE_200, Constants.HTTP_RES_CODE_200_VALUE, null); } // 返回成功,沒有data值 public BaseResponse setResultSuccess(String msg) { return setResult(Constants.HTTP_RES_CODE_200, msg, null); } // 通用封装 public BaseResponse setResult(Integer code, String msg, Object data) { return new BaseResponse(code, msg, data); } // 调用数据库层判断 public Boolean toDaoResult(int result) { return result > 0 ? true : false; } }

4.具体用法
@RestController public class WeiXinAppServiceImpl extends BaseApiService implements WeiXinAppService { //具体用法(测试) public BaseResponse getApp() { return setResultError("系统错误!"); }}

    推荐阅读