参数校验及统一异常捕获

参考地址:

https://mp.weixin.qq.com/s?__biz=MzUxOTc4NjEyMw==&mid=2247491462&idx=2&sn=fdd8bde9777464e147d0d0efc37bc415&chksm=f9f50462ce828d74dbd64d8f8f98447124ea11c4a1ce46184e7c12d2fab04663b194f916af70&mpshare=1&scene=24&srcid=0810jpENQKrV1d1YWk5mWbBs&sharer_sharetime=1597036682660&sharer_shareid=98ceed04f7760be7a63b97c5ad7b0cea#rd

一、参数校验分类

public class ArgumetValidate {

    /**
     * 限定保存必传字段
     */
    public interface Save{}

    /**
     *限定修改必传字段
     */
    public interface Update{}

}

二、实体类注解

    @NotNull(message="xx不能为空",groups = ArgumetValidate.Update.class)
    private Long appId; 

    @NotBlank(message = "xx不能为空", groups = ArgumetValidate.Save.class)
    private String appName;

三、web层相关注解

 /**
     * 新增
     * @param t
     * @return
     */
    @PostMapping("insert")
    public String insert(@RequestBody @Validated(ArgumetValidate.Save.class) T t) {
        xxService.insert(t);
        return "ok";
    }

 /**
     * 更新
     * @param t
     * @return
     */
    @PostMapping("update")
    public String update(@RequestBody @Validated(ArgumetValidate.Update.class) T t) {
        xxService.update(t);
        return "ok";
    }

四、统一异常捕获

@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ReturnData MethodArgumentNotValidException(MethodArgumentNotValidException e){
        BindingResult bindingResult =  e.getBindingResult();
        StringBuilder sb = new StringBuilder("校验失败:");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sb.append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage()).append(", ");
        }
        return new ReturnData(SysCodeMsg.PARAM_IS_ERROR.getCode(),sb.toString());
    }

    @ExceptionHandler({ConstraintViolationException.class})
    public ReturnData handleConstraintViolationException(ConstraintViolationException e) {
        return new ReturnData(SysCodeMsg.PARAM_IS_ERROR.getCode(),e.getMessage());
    }
    @ExceptionHandler(Exception.class)
    public ReturnData exception(Exception e){
        // 根据不同错误返回不同的信息
        String res;
        if (e instanceof SQLException) { // 非运行异常
            res = "数据库异常:";
            log.error("数据库异常:",e);
        } else if (e instanceof IOException) {
            res = "IO流异常";
            log.error("IO流异常:",e);
        } else if (e instanceof RuntimeException) {// 运行异常
            res = "运行时异常";
            log.error("运行时异常:",e);
        } else {// 错误
            res = "系统错误";
            log.error("系统错误:",e);
        }
        Integer code = SysCodeMsg.SYS_ERROR.getCode();
        //自定义异常
        if (e.getClass().getName().startsWith("com.xx.xx.exceptions")) {
            res = e.getMessage();
            code = SysCodeMsg.FAIL.getCode();
        }
        return new ReturnData(code,res);
    }

 

posted @ 2020-09-25 17:34  炫舞风中  阅读(269)  评论(0编辑  收藏  举报