当前位置:网站首页>How to define a unified response object gracefully

How to define a unified response object gracefully

2022-07-05 03:28:00 Magnon AMG

Hope is being able to see there is light despite all of the darkness

At present, the mainstream development methods are front-end and back-end separation , Define a general and unified return format , It is very necessary to communicate at the front and back end , Everyone understands based on this agreement , Can quickly locate problems , Next, let's talk about how to define a unified response object gracefully

Design a unified response object

Define a unified response object , The things that this object needs to accomplish are

  • There is a response status code
  • There is a response message string
  • There is a generic data carrier
  • You can also define a method , It is used to identify whether there is an error in the transfer of the current object

The following is what I used to use , For reference only

// Omit getter and setter etc. 
public class ApiResult<T> {
	/**
	 *  Status identification 
	 */
	private Integer code;
	/**
	 *  The information carried 
	 */
	private String msg;
	/**
	 *  Carry data body 
	 */
	private T data;
	
	/**
	 *  Is it wrong 
	 * @return	true or false
	 */
	public boolean isError() {
		return code != HttpStatus.OK.value();
	}
}

Because every time new Object returns , Not very elegant , So I will also use an auxiliary generation class , It is specially used to generate response objects quickly and easily

public class ApiResultGenerator {
	
	private static final Integer OK = 200;
	
	private static final Integer SERVER_ERROR = 500;
	
	private static final Integer NOT_FOUND = 404;
	
	public static ApiResult success() {
		ApiResult result = new ApiResult();
		result.setCode(OK);
		return result;
	}
	
	public static <T> ApiResult<T> success(T data) {
		ApiResult<T> result = new ApiResult<>();
		result.setCode(OK);
		result.setData(data);
		return result;
	}
	
	public static ApiResult failure() {
		ApiResult result = new ApiResult();
		result.setCode(SERVER_ERROR);
		result.setMsg("server error...");
		return result;
	}
	
	public static ApiResult failure(String msg) {
		ApiResult result = new ApiResult();
		result.setCode(SERVER_ERROR);
		result.setMsg(msg);
		return result;
	}
	
	public static <T> ApiResult<T> failure(String msg, T data) {
		ApiResult<T> result = new ApiResult();
		result.setCode(SERVER_ERROR);
		result.setMsg(msg);
		result.setData(data);
		return result;
	}
	
	//... Free play 
}

Now that the unified response object has been established , According to our habit, it's time to start testing

/**
	 *  Return without data Of ( Success stories )
	 * @return
	 */
	public ApiResult getPaperInfoSuccess() {
		if (log.isInfoEnabled()) {
			log.info(" Receive get paper Information request ...");
		}
		//... Business logic 
		if (log.isInfoEnabled()) {
			log.info(" Acquisition complete paper Information request , Ready to return object information ");
		}
		return ApiResultGenerator.success();
	}

You can pay attention to , This json The object is the bridge between us and the front end , adopt isError This method can determine whether the interface has failed , This method can also be used in microservice invocation

image-20220213232544346

Another example of failure

/**
	 *  Return to carry data Of ( Failure example )
	 * @return
	 */
@GetMapping("/getStrSF")
public ApiResult<List<String>> getTestStrFailure() {
    if (log.isInfoEnabled()) {
        log.info(" Receive get Str Collection request ...");
    }

    ApiResult<List<String>> response;
    try {
        response = getStrs();
        // Manually simulate an exception 
        int i = 1/0;
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error(" obtain Str Collection error ");
        }
        return ApiResultGenerator.failure(" obtain Str Set exception ", null);
    }
    if (log.isInfoEnabled()) {
        log.info(" Acquisition complete Str Collection request , Ready to return object information : {}", JSON.toJSONString(response));
    }
    return response;
}

It can be noted that , return data yes null, Because it is directly assigned as null 了 ,

image-20220214071332603

原网站

版权声明
本文为[Magnon AMG]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140740364351.html