乐趣区

java-springboot-自定义错误

  • 自定义返回 result
public class CustomResult {

    /**
     * 状态响应码
     */
    private String  code;

    /**
     * 响应信息
     */
    private String message;

    /**
     * 响应数据
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private Object data;

    /**
     * 数据总数
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private Long totalCount;

    public CustomResult setCode(CustomResultCode customResultCode) {this.code = customResultCode.code();
        return this;
    }

    public String getCode() {return code;}

    public String getMessage() {return message;}

    public CustomResult setMessage(String message) {
        this.message = message;
        return this;
    }

    public Object getData() {return data;}

    public CustomResult setData(Object data) {
        this.data = data;
        return this;
    }

    public Long getTotalCount() { return totalCount;}

    public CustomResult setTotalCount(Long totalCount) {
        this.totalCount = totalCount;
        return this;
    }

}
  • 自定义错误 code
public enum CustomResultCode {Custom_SUCCESS("1"), // 成功
    Custom_Fail("0"); // 失败

    private final String code;

    CustomResultCode(String code) {this.code = code;}

    public String code() {return code;}
}
  • 测试
@RequestMapping("test-custom-exception")
    public void testCustomException() {throw new CustomException("自定义错误");
    }
  • 结果
{"code":"0","message":"自定义错误"}
退出移动版