项目构建之服务之间的接口调用返回值封装和异常封装(附代码)

目录

介绍:

ResultUtil

ApiResult

 ApiException extends RuntimeException

ApiInfo

ResultCode

捕获异常处理类ApiExceptionHandle


介绍:

接口调用:项目构建之服务之间的接口调用通常需要一个通用的返回值,即ApiResult。

异常处理:业务处理时,会需要有很多地方进行逻辑卡控,抛出异常等,也需要返回一个通用的封装对象,即ApiResult。

ResultUtil的作用:就是将原本返回的对象进行再次封装,封装成ApiResult通用对象

 


ResultUtil

import com.google.gson.Gson;
import org.json.JSONObject;
import org.springframework.http.HttpStatus;

public class ResultUtil {
    private static ApiInfo basicInfo = new ApiInfo();

    public ResultUtil() {
    }

    public static ApiInfo getBasicInfo() {
        return basicInfo;
    }

    public static ApiResult setResult(Integer httpCode, ResultCode resultCode, Object object, String addiInfo) {
        ApiResult<Object> result = new ApiResult();
        result.setHttpCode(httpCode);
        result.setCode(resultCode.getCode());
        result.setMsg(resultCode.getMsg());
        result.setMsgCh(resultCode.getMsgCh());
        result.setData(object);
        result.setAddiInfo(addiInfo);
        result.setBasicInfo(basicInfo);
        return result;
    }

    public static ApiResult success(Object object, String addiInfo) {
        return setResult(HttpStatus.OK.value(), ResultCode.SUCCESS, object, addiInfo);
    }

    public static ApiResult success(ResultCode resultCode) {
        return setResult(HttpStatus.OK.value(), resultCode, (Object)null, (String)null);
    }

    public static ApiResult success(Object object) {
        return setResult(HttpStatus.OK.value(), ResultCode.SUCCESS, object, (String)null);
    }

    public static ApiResult success(Integer httpCode, Object object, String addiInfo) {
        return setResult(httpCode, ResultCode.SUCCESS, object, addiInfo);
    }

    public static ApiResult success() {
        return success((Object)null, (String)null);
    }

    public static ApiResult error(ResultCode resultCode) {
        return setResult(HttpStatus.BAD_REQUEST.value(), resultCode, (Object)null, (String)null);
    }

    public static ApiResult error(ResultCode resultCode, String addiInfo) {
        return setResult(HttpStatus.BAD_REQUEST.value(), resultCode, (Object)null, addiInfo);
    }

    public static ApiResult error(Integer httpCode, ResultCode resultCode, String addiInfo) {
        return setResult(httpCode, resultCode, (Object)null, addiInfo);
    }

    public static ApiResult error(ResultCode resultCode, String msgEn, String msgCh) {
        ApiResult result = new ApiResult();
        result.setHttpCode(HttpStatus.BAD_REQUEST.value());
        result.setCode(resultCode.getCode());
        result.setMsg(msgEn);
        result.setMsgCh(msgCh);
        return result;
    }

    public static ApiResult handleApiException(Exception e) {
        if (e instanceof ApiException) {
            ApiException apiException = (ApiException)e;
            return apiException.getApiResult();
        } else {
            return error(ResultCode.UNKONW_ERROR, e.toString());
        }
    }

    public static ApiResult<Object> getApiResult(String JsonStr) {
        ApiResult<Object> result = new ApiResult();
        JSONObject jsonObject = new JSONObject(JsonStr);
        ApiInfo apiInfo = new ApiInfo();
        Object object = jsonObject.get("basicInfo");
        if (null != object) {
            Gson gson = new Gson();
            apiInfo = (ApiInfo)gson.fromJson(object.toString(), ApiInfo.class);
        }

        result.setBasicInfo(apiInfo);
        result.setCode(jsonObject.getInt("code"));
        result.setMsg(jsonObject.getString("msg"));
        result.setMsgCh(jsonObject.getString("msgCh"));
        Object addInfo = jsonObject.get("addiInfo");
        if (addInfo != null) {
            result.setAddiInfo(addInfo.toString());
        }

        object = jsonObject.get("data");
        if (null != object) {
            result.setData(object);
        }

        return result;
    }

    public static String getCodeInfo() {
        boolean ifStart = true;
        String jsonStr = "{[";
        ResultCode[] var2 = ResultCode.values();
        int var3 = var2.length;

        for(int var4 = 0; var4 < var3; ++var4) {
            ResultCode resultCode = var2[var4];
            if (ifStart) {
                jsonStr = jsonStr + "{";
                ifStart = false;
            } else {
                jsonStr = jsonStr + ",{";
            }

            jsonStr = jsonStr + "\"code\":" + resultCode.getCode() + ",";
            jsonStr = jsonStr + "\"msg\":\"" + resultCode.getMsg() + "\",";
            jsonStr = jsonStr + "\"msgCh\":\"" + resultCode.getMsgCh() + "\"}";
        }

        jsonStr = "]}";
        return jsonStr;
    }
}

 

 

ApiResult

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel(
    value = "ApiResult",
    description = "统一错误码"
)
public class ApiResult<T> {
    @ApiModelProperty("http专用错误码")
    private Integer httpCode;
    @ApiModelProperty(
        value = "Hierway 业务错误码",
        example = "200: Success; 201: Failure"
    )
    private Integer code;
    @ApiModelProperty("错误码信息")
    private String msg;
    @ApiModelProperty("中文错误码信息")
    private String msgCh;
    @ApiModelProperty("错误码额外信息,当msg不能满足的情况下使用")
    private String addiInfo;
    @ApiModelProperty("基本信息,比如模块名,IP等")
    private ApiInfo basicInfo;
    @ApiModelProperty("返回值的内容")
    private T data;

    public ApiResult() {
    }

    get set tostring  省略
}

 

 

 ApiException extends RuntimeException

public class ApiException extends RuntimeException {
    private ApiResult apiResult;

    public ApiResult getApiResult() {
        return this.apiResult;
    }

    public void setApiResult(ApiResult apiResult) {
        this.apiResult = apiResult;
    }

    public ApiException(ResultCode resultCode) {
        this.apiResult = ResultUtil.error(resultCode);
    }

    public ApiException(ResultCode resultCode, String addiInfo) {
        this.apiResult = ResultUtil.error(resultCode, addiInfo);
    }

    public String toString() {
        return "ApiException{apiResult=" + this.apiResult + '}';
    }
}

 

 

ApiInfo

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel(
    value = "ApiInfo",
    description = "API基本信息"
)
public class ApiInfo {
    @ApiModelProperty("服务模块名")
    private String module_name = "unknown name";
    @ApiModelProperty("服务模块IP地址")
    private String ip_address = "0.0.0.0";
    @ApiModelProperty("服务模块端口号")
    private short udp_port = 0;
    @ApiModelProperty("其它信息")
    private String addiInfo = "no additional information";

    ApiInfo() {
    }
    
    get set tostring 省略
}

 

 

ResultCode

public enum ResultCode {
    UNKONW_ERROR(-1, "Unknown error", "未知错误"),
    SUCCESS(200, "Success", "成功"),
    FAILURE(201, "Failure", "失败"),
    NO_DATA_FOUND(202, "Data not found", "未找到数据"),
    COMMON_BASE_CODE(1000, "Common Base Error Code", "通用基本错误码"),
    COMMON_FAILSURE(1001, "Failsure", "失败"),
    COMMON_NO_DATA_FOUND(1002, "Data not found", "未找到数据"),
    ADD_FAILED(1003, "Add failed", "添加失败"),
    UPDATE_FAILED(1004, "Updated failed", "更新失败"),
    DELETE_FAILED(1005, "Delete failed", "删除失败"),
    DATA_ALREADY_EXIST(1006, "Data already existed", "数据已经存在"),
    NOT_SUITABLE_OPERATION(1007, "Not suitable operation", "不适合的操作"),
    DATABASE_OP_FAILED(1008, "Operate database failed", "操作数据库失败"),
    NO_PERMISSION(1009, "Permission is needed", "权限不够,需要开通权限"),
    SERVER_ERROR(1010, "Server error", "服务器错误"),
    AUTH_ERROR(1011, "Authentication failed ", "鉴权失败"),
    PARAMS_ERROR(1012, "Parameter error", "参数错误"),
    JSON_PARSE_ERROR(1013, "Json parse error", "JSON解析错误"),
    ILLEAGAL_STRING(1014, "Illegal string", "非法字符串"),
    CERTIFICATE_EXPIRED(1015, "Client certificate has expired or is not yet valid", "客户端证书过期或已无效"),
    CERTIFICATE_INVALID(1016, "Client certificate is untrusted or invalid.", "客户端证书不可信或无效"),
    SYSTEM_BASE_CODE(2000, "System Base Error Code", "系统基本错误码"),
    DO_NOT_OPERATE(10000, "Do not operate", "不操作"),
    THERE_ARE_STILL_PROCESSES_WITHOUT_MOUNT_PRODUCTIVITY_UNITS(10001, "There are still processes without mount productivity units", "未定义"),
    THE_PRODUCTIVITY_UNIT_HAS_BEEN_USED(10002, "The productivity unit has been used", "未定义"),
    NO_NEED_CONFIGURE(10003, "The process does not require configuration of a productivity unit", "未定义");

    private Integer code;
    private String msg;
    private String msgCh;

    private ResultCode(Integer code, String msg, String msgCh) {
        this.code = code;
        this.msg = msg;
        this.msgCh = msgCh;
    }

    public Integer getCode() {
        return this.code;
    }

    public String getMsg() {
        return this.msg;
    }

    public String getMsgCh() {
        return this.msgCh;
    }
}

 

 

 

捕获异常处理类ApiExceptionHandle

@ControllerAdvice
public class ApiExceptionHandle {
    private final static Logger logger = LoggerFactory.getLogger(ApiExceptionHandle.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ApiResult handle(Exception e) {
        logger.error("全局异常:{}", e);
        return ResultUtil.handleApiException(e);
    }
}

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值