Currently our return is to throw the entity class directly to the requester, which is very unfriendly because there is no uniform format and the requester does not know whether the request was successful or not, there is nothing to judge and no declarative return.

This article provides a uniform friendly return for all interfaces.

Determine the return structure

First, we decide what the format of our interface should be, and then implement the following step by step.

{
	"code": 200."msg": "ok"."data": ""
}
Copy the code

• The code field indicates the status code, which can be used by the caller as the basis for subsequent logic. For example, if the code value is 200, the operation succeeds and there is no logical error. In this case, the user can be prompted that the operation succeeds. If the value of code is not 200, the operation fails. For example, if the value of code is 1001, the user name already exists.

• The MSG field is used as an additional statement, for example, if the state is 1001, the MSG can be a statement like username exists to help the caller understand it better.

• The data field usually returns specific business data when the code value is 200, which can be an array or an object.

Create return code

Create a common directory in your project and create apicode.java as follows:

package com.foxescap.wxbox.common;

/** * Global interface status code *@author xfly
 */
public enum ApiCode {
    /** * universal success */
    API_OK(200."ok"),
    /** * The username already exists */
    API_USERNAME_EXIST(1001."username exists");

    private final int code;

    private final String msg;

    ApiCode(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public int code(a) {
        return this.code;
    }

    public String getMsg(a) {
        return this.msg; }}Copy the code

Each subsequent different error code needs to be added here, and then the enumeration variable is called here. This can be a bit cumbersome, but as the project grows, it will do a good job of managing the status code.

Creating a return class

Create the common directory in your project and create an httpresponse.java file:

package com.foxescap.wxbox.common;

import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.Serializable;

/ * * *@author xfly
 * @param <T>
 */
@Data
@AllArgsConstructor
@JsonPropertyOrder({"code"."msg"."data"})
public class ApiResponse<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    /** * Custom return code */
    private int code;

    /** * Custom return description */
    private String msg;

    /** * returns data */
    private T data;

    /** * Successfully returned with no data **@returnCustom ApiResponse object */
    public static ApiResponse<Object> success(a) {
        return new ApiResponse<>(ApiCode.API_OK.code(), ApiCode.API_OK.getMsg(), "");
    }

    /** * Successfully returned with data **@paramObject returns data *@param<T> Returns data type *@returnCustom ApiResponse object */
    public static <T> ApiResponse<T> success(T object) {
        return new ApiResponse<>(ApiCode.API_OK.code(), ApiCode.API_OK.getMsg(), object);
    }

    /** * returns ** on failure@paramApiCode error code *@returnCustom ApiResponse object */
    public static ApiResponse<Object> fail(ApiCode apiCode) {
        return new ApiResponse<>(apiCode.code(), apiCode.getMsg(), ""); }}Copy the code

Using return classes

Let’s change the interface return in Controller. Instead of returning the entity class directly, we’ll encapsulate our return class and return it to the caller:

@GetMapping("/user/{username}")
public ApiResponse<User> findUserByUsername(@PathVariable(name = "username") String username) {
    return ApiResponse.success(userService.findByUsername(username));
}
Copy the code