zoukankan      html  css  js  c++  java
  • SpringMvc的 @Valid 拦截到的异常如何抛出

    SpringMvc中,校验参数可以使用 @Valid 注解,同时在相应的对象里使用

    @NotBlank( message = "昵称不能为空")
    @NotNull( message = "ID不能为空")
    @Pattern(
      message = "不能包括空格"
      , regexp = "\S+"
    )

    等等。

    这个校验会把所有的参数都校验一遍,所以它的异常里会好些列表,直接使用e.getMessage(),会输出很多累赘的东西

    一个好的解决办法

    @Valid 注解校验住的异常是 org.springframework.validation.BindException

    所以可以添加一个异常拦截器,专门拦截,并且解析这种异常

    具体如下:

    package cn.jiashubing.config;
    
    import cn.jiashubing.result.ResultModel;
    import org.springframework.validation.BindException;
    import org.springframework.validation.ObjectError;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import java.util.List;
    
    /**
     * @author jiashubing
     * @since 2019/6/17
     */
    @ControllerAdvice
    public class BingExceptionHandler {
    
        @ExceptionHandler(BindException.class)
        @ResponseBody
        public ResultModel handleBindException(Exception e) {
            //打印校验住的所有的错误信息
            StringBuilder sb = new StringBuilder("参数错误:[");
            List<ObjectError> list = ((BindException) e).getAllErrors();
            for (ObjectError item : list) {
                sb.append(item.getDefaultMessage()).append(',');
            }
            sb.deleteCharAt(sb.length() - 1);
            sb.append(']');
    
            String msg = sb.toString();
            return new ResultModel(false, msg);
        }
    
    }

    原创文章,欢迎转载,转载请注明出处!

  • 相关阅读:
    超强问卷调查系统源码购买及二次开发
    asp.net core mvc上传大文件解决方案
    asp.net core mvc发布后显示异常错误信息的方法
    基于.net core 2.0+mysql+AceAdmin搭建一套快速开发框架
    改造kindeditor支持asp.net core mvc上传文件
    Centos7 Nginx安装使用
    Centos7 守护进程supervisord 安装使用
    Centos7 .net core 2.0安装使用
    Centos7 Mysql安装
    Centos7 Redis安装
  • 原文地址:https://www.cnblogs.com/acm-bingzi/p/springmvc_valid.html
Copyright © 2011-2022 走看看