美文网首页
接口层代码逻辑

接口层代码逻辑

作者: 黄靠谱 | 来源:发表于2019-07-17 16:43 被阅读0次

    接口层代码逻辑

    1. 返回值是一个Result对象,分为 code、data、errorMsg等。这样如果调用异常,可以告知调用方异常的类型,更友好
    1. 校验参数,并且根据参数的校验情况,返回不同的错误码(封装成枚举类)(千万不要再去做逻辑加工,否则就坑爹了)
        ValidateUtilEntity checkResult= this.validateParam();
        if( checkResult.isFail()){
            return checkResult.getResult();
        }
    
    1. 加工参数(check + fill)
      ValidateUtilEntity checkHeaderResult= this.checkAndProcessHeader();

    2. 执行业务逻辑,并且做好异常的处理

    3. 封装返回结果为 Result对象

    Demo

    工具类 ValidateUtilEntity.java

    /**
     * @program: 
     * @create: 2019-07-17 10:48
     * 校验工具类
     * 1. 如果校验成功,则校验函数返回ValidateUtilEntity.success(),状态码成功
     * 2. 如果校验失败,则校验函数返回ValidateUtilEntity.fail(错误信息),状态码失败,且包含失败的Result
     **/
    public class ValidateUtilEntity {
        private boolean isSuccess;
        private static Result result = new Result();
    
        public ValidateUtilEntity(boolean isSuccess) {
            this.isSuccess = isSuccess;
        }
    
        public ValidateUtilEntity(boolean isSuccess, Result result) {
            this.isSuccess = isSuccess;
            this.result = result;
        }
    
        public static ValidateUtilEntity success() {
            return new ValidateUtilEntity(true);
        }
    
        public static ValidateUtilEntity fail(ResponseCodeEnum responseCodeEnum) {
            result = responseCodeEnum.bindFailureResult(result);
            return new ValidateUtilEntity(false, result);
        }
    
        public static ValidateUtilEntity fail(ResponseCodeEnum responseCodeEnum, String extraErrorMsg) {
            result = responseCodeEnum.bindFailureResult(result, extraErrorMsg);
            return new ValidateUtilEntity(false, result);
        }
        /**
        *方便调用,更直观
        **/
        public boolean isFail() {
            return !isSuccess;
        }
    
        public boolean isSuccess() {
            return isSuccess;
        }
    
        public void setSuccess(boolean success) {
            isSuccess = success;
        }
    
        public Result getResult() {
            return this.result;
        }
    }
    
    

    使用示例

        @PostMapping(value = "rest/json2json/{interfaceName}")
        public Result restXml2Json(@RequestBody String body, @PathVariable("interfaceName") String interfaceName,
                                   HttpServletRequest request) {
            Result<Object> result = new Result<>();
            InterfaceDetail interfaceDetail = interfaceDetailService.getInterfaceByName(interfaceName);
            if (interfaceDetail == null) {
                return ResponseCodeEnum.PARAM_ERROR.bindFailureResult(result);
            }
    
            HttpHeaders requestHeaders = new HttpHeaders();
            ValidateUtilEntity checkHeaderResult = this.checkAndProcessHeaderInfo(requestHeaders, interfaceDetail, request);
            if (checkHeaderResult.isFail()) {
                return checkHeaderResult.getResult();
            }
            
            log.debug("{}请求:{}", interfaceName, body);
            try {
                String resultBody = this.invokeRestTemplate(body, requestHeaders, interfaceDetail);
                log.debug("{}返回:{}", interfaceDetail.getName(), resultBody);
                return result.successGlobalCode(JSONObject.parseObject(resultBody));
            } catch (Exception e) {
                log.error("调用接口异常:", e);
                return ResponseCodeEnum.INVOKE_ERROR.bindFailureResult(result, e.getMessage());
            }
        }
    
        private String invokeRestTemplate(String body, HttpHeaders requestHeaders, InterfaceDetail interfaceDetail) {
            HttpEntity<String> requestEntity = new HttpEntity<>(body, requestHeaders);
            ResponseEntity<String> responseEntity = restTemplate.exchange(interfaceDetail.getUrl(), HttpMethod.POST,
                    requestEntity, String.class);
            return responseEntity.getBody();
        }
    
        private ValidateUtilEntity checkAndProcessHeaderInfo(HttpHeaders requestHeaders, InterfaceDetail interfaceDetail, HttpServletRequest request) {
            requestHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
            // 设置头部
            if (StringUtils.isNotBlank(interfaceDetail.getHeader())) {
                String[] headerKey = interfaceDetail.getHeader().split(",");
                for (String key : headerKey) {
                    String value = request.getHeader(key);
                    if (null == value) {
                        return ValidateUtilEntity.fail(ResponseCodeEnum.PARAMHEADER_ERROR, key);
                    }
                    requestHeaders.add(key, value);
                }
            }
            return ValidateUtilEntity.success();
        }
    

    错误返回值的枚举类

    public enum ResponseCodeEnum {
        OK("0", "OK"),
        PARAM_ERROR("EC002M01", "未找到接口相关配置"),
        PARAMHEADER_ERROR("EC002M02", "缺少请求头信息:%s"),
        PARSE_ERROR("EC002M03", "格式化参数异常"),
        PARSERESULT_ERROR("EC002M04", "解析返回结果异常"),
        INVOKE_ERROR("EC002M10", "调用接口异常:%s"),
        OTHER_ERROR("EC002M99", "其他错误");
    
        private String code;
        private String msg;
    
        private ResponseCodeEnum(String code, String msg) {
            this.code = code;
            this.msg = msg;
        }
    
        //根据枚举的code获取msg的方法
        public static String getMsgByCode(String code){
            for(ResponseCodeEnum responseEnum : ResponseCodeEnum.values()) {
                if(responseEnum.getCode().equals(code)){
                    return responseEnum.msg;
                }
            }
            return null;
        }
    
        public <T> Result<T> bindFailureResult(Result<T> result, Object... args) {
            String msgResult = String.format(this.msg, args);
            return result.failureGlobal(this.code, msgResult);
        }
    
        public String getCode() {
            return code;
        }
    
    
        public String getMsg() {
            return msg;
        }
    }
    

    相关文章

      网友评论

          本文标题:接口层代码逻辑

          本文链接:https://www.haomeiwen.com/subject/uvkclctx.html