SpringBoot参数校验
in 默认分类 with 0 comment

SpringBoot参数校验

in 默认分类 with 0 comment

maven

<!-- WEB依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 参数校验 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

全局异常处理

@ControllerAdvice
@Slf4j
public class MyControllerAdvice {
    /**
     * 参数校验不通过异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONObject methodArgumentNotValidException(MethodArgumentNotValidException e) {
        System.out.println(e.getMessage());
        System.out.println("这是methodArgumentNotValidException");
        return new JSONObject();
    }

    /**
     * 参数校验不通过异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(BindException.class)
    public JSONObject bindException(BindException e) {
        System.out.println(e.getMessage());
        System.out.println("这是bindException");
        return new JSONObject();
    }
}

注:原本只捕获了MethodArgumentNotValidException这个异常,但发现只有post才能正确的校验,get请求的时候抛出了另外一个异常,所以需要把两个都捕获了。

Responses