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请求的时候抛出了另外一个异常,所以需要把两个都捕获了。
本文由 visionki 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: Mar 17, 2021 at 07:44 am