首先要封装一个响应的枚举,将一些常见的错误写入,一般状态码需要与前端一起制定,以便前端提示错误信息以及发生错误的处理逻辑。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| package com.yww.demo.util;
public enum ResultCode {
SUCCESS(200, "成功"),
FAILED(500, "服务器发生错误");
private Integer status; private String message;
ResultCode(Integer status, String message) { this.status = status; this.message = message; }
public Integer getStatus() { return this.status; }
public String getMessage() { return this.message; }
}
|
然后是数据返回的封装类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| package com.yww.demo.util;
import lombok.Data;
@Data public class Result<T> {
private Integer code;
private String message;
private T data;
private Result() {}
public Result(Integer code, String message, T data) { this.code = code; this.message = message; this.data = data; }
public static <T> Result<T> success() { return new Result<>(ResultCode.SUCCESS.getStatus(), ResultCode.SUCCESS.getMessage(), null); }
public static <T> Result<T> success(T data) { return new Result<>(ResultCode.SUCCESS.getStatus(), ResultCode.SUCCESS.getMessage(), data); }
public static <T> Result<T> failure() { return new Result<>(ResultCode.FAILED.getStatus(), ResultCode.FAILED.getMessage(),null); }
public static <T> Result<T> failure(String message) { return new Result<>(ResultCode.FAILED.getStatus(), message,null); }
public static <T> Result<T> failure(ResultCode resultCode) { return new Result<>(resultCode.getStatus(), resultCode.getMessage(),null); }
}
|