我在项目中做的 rest 接口全局统一格式返回的处理

    • 使用了 Lombok 插件,所以需要引入依赖
    1. <dependency>
    2. <groupId>org.projectlombok</groupId>
    3. <artifactId>lombok</artifactId>
    4. <optional>true</optional>
    5. </dependency>
    • 定义状态码的枚举类
    1. @Getter
    2. public enum StatusCode {
    3. SUCCESS(100,"Request is successful"), // 成功返回
    4. FAIL(109, "Request is failed"), // 失败返回
    5. INNER_ERROR(500, "Unknown error"); // 未知错误
    6. private Integer code;
    7. private String message;
    8. StatusCode(Integer code, String message) {
    9. this.code = code;
    10. this.message = message;
    11. }
    12. }
    • 定义 Result 对象,对状态码、信息和数据进行了封装
    1. @Data
    2. @AllArgsConstructor
    3. public class Result {
    4. private Integer code;
    5. private String message;
    6. private Object data;
    7. public Result() {
    8. }
    9. private void setResultCode(StatusCode statusCode) {
    10. this.code = statusCode.getCode();
    11. this.message = statusCode.getMessage();
    12. }
    13. public static Result success() {
    14. Result result = new Result();
    15. result.setResultCode(StatusCode.SUCCESS);
    16. return result;
    17. }
    18. public static Result success(Object data) {
    19. Result result = new Result();
    20. result.setResultCode(StatusCode.SUCCESS);
    21. result.setData(data);
    22. return result;
    23. }
    24. public static Result fail() {
    25. Result result = new Result();
    26. result.setResultCode(StatusCode.FAIL);
    27. return result;
    28. }
    29. public static Result fail(StatusCode statusCode) {
    30. Result result = new Result();
    31. result.setResultCode(statusCode);
    32. return result;
    33. }
    34. public static Result fail(String message) {
    35. Result result = new Result();
    36. result.setCode(StatusCode.FAIL.getCode());
    37. result.setMessage(message);
    38. return result;
    39. }
    40. }
    • 在接口中使用
    1. @PostMapping("/test")
    2. public Result test() {
    3. return Result.success();
    4. }