数据校验工具类

思路,

 1、传入要校验的属性以及如果校验不过提示信息

 2、如果数据校验不过返回json 格式信息。

 3、不满足条件抛出自定义异常,然后在异常处理器中获取信息,return 信息

一、自定义异常

public class LyonException extends RuntimeException{
    private static final long serialVersionUID = 1L;
    
    private String msg;
    private int code = 500;
    code 默认是500
    public LyonException(String msg) {
        super(msg);
        this.msg = msg;
    }

    public LyonException(String msg, int code) {
       super(msg);
       this.msg = msg;
       this.code = code;
   }

 

二、异常处理器

/**
 * 异常处理器
 * @author    lyon
 * @date    2018年3月2日
 */
@RestControllerAdvice
public class LyonExceptionHandler {

    
    @ExceptionHandler(LyonException.class)
    public R handlerLyonException(LyonException e){
        R r = new R();
        r.put("code", e.getCode());
        r.put("msg", e.getMessage());
        return r;
    }
}

三、返回值R

public class R extends HashMap<String, Object> {
    private static final long serialVersionUID = 1L;

    public R() {
        put("code", 0);
        put("msg", "操作成功");
    }

    public static R error() {
        return error(1, "操作失败");
    }

    public static R error(String msg) {
        return error(500, msg);
    }

    public static R error(int code, String msg) {
        R r = new R();
        r.put("code", code);
        r.put("msg", msg);
        return r;
    }

    public static R ok(String msg) {
        R r = new R();
        r.put("msg", msg);
        return r;
    }
View Code

四、工具类

/**
 * 数据校验
 * @author    lyon
 * @date    2018年3月2日
 */
public abstract class Assert {

    /**
     * @param str 校验的字符串
     * @param msg 提示信息
     */
    public static void isBlank(String str,String msg){
        if(StringUtils.isBlank(str)){
            throw new LyonException(msg);
        }
    }
    
    public static void isNull(Object object, String message) {
        if (object == null) {
            throw new LyonException(message);
        }
    }
}

五、测试

    @GetMapping("/test")
    @ResponseBody
    public R hello(String name) {
        Assert.isBlank(name, "用户名不能为空");
        return R.ok();
    }

原文地址:https://www.cnblogs.com/lyon91/p/8492355.html