Java interface unified style return template

background

In the development of interfaces, a fixed return style is generally required. When the interface is successful or failed, the unified return is carried out according to this format. In this way, the joint debugging between interfaces with other people will not appear disorderly. If this fixed format is placed in each interface of Java to be processed separately, it will be very tedious in interface development. Therefore, an entity class can be encapsulated at this time to return the contents of the fixed template format uniformly.

Packaging template

First look at the interface code and return format before encapsulation:

/**
 * User modification
 * @return Return modified user information
 */
@PutMapping(value = "update")
public User update(@RequestBody User user) {
        User updatedUser = userService.update(user);
        return updatedUser;
}
{
    "userId": "0d67cfa7-f6a1-46b6-8e5a-b605afc98c44",
    "username": "ww",
    "password": "123456",
    "status": 0,
    "createTime": 310863886132307,
    "updateTime": 312955781619836
}

Obviously, although the original content return is very intuitive, if an error occurs, the interface return will be more unnatural, and even the underlying error will be exposed to the outside world. Here is the next simple unified interface style encapsulation:

Enumeration class ResponseCode: define return code and prompt msg

First, we define an enumeration class to encapsulate the returned code and prompt msg. Of course, we can also encapsulate other information, such as status, which can be freely selected according to our own project.

package com.server.config;

/**
 * @Package com.server.config
 * @Author wuzy
 * @Date 2019/10/30 14:47
 * @Version V1.0
 * @Description: code Code encapsulation enumeration class
 */

public enum ResponseCode {
    /** Success */
    SUCCESS("200", "Success"),

    /** operation failed */
    ERROR("500", "operation failed");

    private ResponseCode(String value, String msg){
        this.val = value;
        this.msg = msg;
    }

    public String val() {
        return val;
    }

    public String msg() {
        return msg;
    }

    private String val;
    private String msg;
}

Encapsulation class ResultData: define code, msg and data

Then we define a encapsulation class ResultData, which is used to encapsulate the uniform format when the interface returns. Here, we define three properties, namely status code, prompt message msg and returned data. Here is the code:

package com.server.config;

import lombok.Data;

/**
 * @Package com.server.config
 * @Author wuzy
 * @Date 2019/10/30 14:38
 * @Version V1.0
 * @Description: Return to style encapsulation
 */
@Data
public class ResultData {

    private String code;

    private String msg;

    private Object data;

    public static ResultData success(Object data) {
       return resultData(ResponseCode.SUCCESS.val(), ResponseCode.SUCCESS.msg(), data);
    }

    public static ResultData success(Object data, String msg) {
        return resultData(ResponseCode.SUCCESS.val(), msg, data);
    }

    public static ResultData fail(String code, String msg) {
        return resultData(code, msg, null);
    }

    public static ResultData fail(String code, String msg, Object data) {
        return resultData(code, msg, data);
    }

    private static ResultData resultData(String code, String msg, Object data) {
        ResultData resultData = new ResultData();
        resultData.setCode(code);
        resultData.setMsg(msg);
        resultData.setData(data);
        return resultData;
    }
}

You can expand methods, attributes and other contents according to your own project requirements.

Test case

Here, we use the save() method in UserController to test and see the effect after adding a unified style. First, we look at this method:

    /**
     * User save
     * @return Return saved user information
     */
    @PostMapping(value = "save")
    @ApiOperation(value = "Save user information", notes = "Save user details")
    public ResultData save(@RequestBody User user) {
        try {
            User savedUser = null;
            if (user != null) {
                if (StringUtils.isEmpty(user.getUserId())) {
                    user.setUserId(UUID.randomUUID().toString());
                }
                savedUser = userService.save(user);
                                // int i = 1/0; / / release this line of code when testing exceptions
            }
            return ResultData.success(savedUser);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.fail(ResponseCode.ERROR.val(), "Exception occurred during user saving,Please check!");
        }
    }

Let's first look at the success (that is, calling the success method)

{
  "code": "200",
  "msg": "Success",
  "data":  {
      "userId": "0d67cfa7-f6a1-46b6-8e5a-b605afc98c44",
      "username": "ww",
      "password": "123456",
      "status": 0,
      "createTime": 310863886132307,
      "updateTime": 312955781619836
    }
}

Take a look at the error prompt when an exception occurs or a save fails. Here, use 1 / 0 exception to test. The results are as follows:

{
  "code": "500",
  "msg": "Exception occurred during user saving,Please check!",
  "data": null
}

Here, basically the template of interface style is also introduced. If there is any inaccuracy, please leave a message for more advice.

WeChat public address: source bay

Welcome to my WeChat public address: source bay. This public number will share the relevant source code and related development technology from time to time, grow together and make progress together.

Blog:

  • Jianshu: https://www.jianshu.com/u/91378a397ffe
  • csdn: https://blog.csdn.net/ZhiyouWu
  • Open source China: https://my.oschina.net/u/3204088
  • Nuggets: https://juejin.im/user/5b5979efe51d451949094265
  • Blog Park: https://www.cnblogs.com/zhiyouwu/
  • WeChat public address: source bay
  • Wechat: WZY1782357529 (welcome to communicate)

Keywords: Java Lombok

Added by Amitk on Wed, 30 Oct 2019 10:42:09 +0200