RestFul接口返回数据工具类

明确返回数据格式

  • status(是否成功)
  • code(响应码)
  • mas(错误信息)
  • data(返回数据资源)
因此创建返回对象
import lombok.Data;

import java.io.Serializable;

@Data
public class ResponseJson  implements Serializable {

    public static final Integer CODE_SUCCESSED = 200;
    public static final Integer CODE_ERROR = 500;

    /**
     * 是否成功
     */
    private boolean status;

    /**
     * 结果信息
     */
    private String message;

    /**
     * 结果返回的数据
     */
    private T data;

    /**
     * 结果返回状态码
     */
    private Integer  code;




    public ResponseJson  ( boolean  status, Integer code, String message) {
        this.status = status;
        this.code = code;
        this.message = message;
    }


    public static ResponseJson  successed() {
        return new ResponseJson(true, CODE_SUCCESSED, "success");
    }

    public static ResponseJson   error() {
        return new ResponseJson(false, CODE_ERROR, "运行时出错.");
    }

    public ResponseJson  setDataAndThen(T data) {
        setData(data);
        return this;
    }

}

返回data数据是Object对象的,通过一个函数式接口处理

@FunctionalInterface
public interface ResponseObject {

    T  get()throws Exception;
}

封装返回数据并且处理全局异常

import org.apache.commons.logging.Log;

public class ResponseWrap {

    public static ResponseJson  wrap(ResponseObject  obj, Log logger) {
        ResponseJson  result = null;
        try {   
            Object data = obj.get();
            result = ResponseJson.successed().setDataAndThen(data);
        } catch (Exception e) {
            result = CommonResult.faild();
            result.setMessage(e.getMessage());
            logger.error("系统运行异常", e);
        }
        return result;
    }

返回Demo

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
@Slf4j
public class SysRoleController {
    private Log logger = LogFactory.getLog(this.getClass());

    @Resource
    private SysRoleService sysRoleService;

    @PostMapping("/getAllRoles")
    public ResponseJson getAllRoles(@RequestBody Map params) {
        return  ResponseWrap.wrap(() -> {
            return  sysRoleService.select(params);
        }, logger);
    }
}

你可能感兴趣的:(RestFul接口返回数据工具类)