Spring 捕捉校验参数异常并统一处理
使用 @Validated ,@Valid ,@NotBlank 之类的,请自行百度,本文着重与捕捉校验失败信息并封装返回出去
参考:
https://mp.weixin.qq.com/s/EaZxYKyC4L_EofWdtyBCpw
https://www.jianshu.com/p/bcc5a3c86480
捕捉校验失败异常信息
@ControllerAdvice
public class WebExceptionHandler {
//处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常,详情继续往下看代码
@ExceptionHandler(BindException.class)
@ResponseBody
public ResponseVO BindExceptionHandler(BindException e) {
String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
return new ResponseVO(message);
} //处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是javax.validation.ConstraintViolationException
@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
public ResponseVO ConstraintViolationExceptionHandler(ConstraintViolationException e) {
String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
return new ResponseVO(message);
} //处理请求参数格式错误 @RequestBody上validate失败后抛出的异常是MethodArgumentNotValidException异常。
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public ResponseVO MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
return new ResponseVO(message);
}
}
如下示例请求参数报错的话,会抛出 BindException 而不是 ConstraintViolationException 和 MethodArgumentNotValidException
@RestController
@RequestMapping("test")
public class TestController { @GetMapping("refund")
public ResponseVO refund(@Valid RefundRequest request) throws Exception {
return new ResponseVO();
}
} @Data
public class RefundRequest implements Serializable {
@NotBlank(message = "订单号不能为空")
private String orderId;
@Min(value = 0, message = "已消费金额金额不能为负数")
private int orderAmt;
}
如果多个请求参数都校验失败,则遇到第一个校验失败就抛出异常,接下来的异常参数不做校验,配置如下
@Configuration
public class WebConfig {
@Bean
public Validator validator() {
ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
.configure()
//failFast的意思只要出现校验失败的情况,就立即结束校验,不再进行后续的校验。
.failFast(true)
.buildValidatorFactory(); return validatorFactory.getValidator();
} @Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
methodValidationPostProcessor.setValidator(validator());
return methodValidationPostProcessor;
}
}
Spring 捕捉校验参数异常并统一处理的更多相关文章
- spring 接口校验参数(自定义注解)
1. 注解类 import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.l ...
- spring boot 输入参数统一校验
1 引入spring boot validate maven 依赖 <!-- 验证 --> <dependency> <groupId>org.hiberna ...
- spring注解式参数校验
很痛苦遇到大量的参数进行校验,在业务中还要抛出异常或者返回异常时的校验信息,在代码中相当冗长,今天我们就来学习spring注解式参数校验. 其实就是:hibernate的validator. 开始啦. ...
- 使用Spring Validation优雅地校验参数
写得好的没我写得全,写得全的没我写得好 引言 不知道大家平时的业务开发过程中 controller 层的参数校验都是怎么写的?是否也存在下面这样的直接判断? public String add(Use ...
- Spring基础系列-参数校验
原创作品,可以转载,但是请标注出处地址:https://www.cnblogs.com/V1haoge/p/9953744.html Spring中使用参数校验 概述 JSR 303中提出了Bea ...
- Validation(3)--全局参数异常校验捕获及返回XML解决
@RestControllerAdvice原创直接上代码,后面再说怎么用1.这个是一个Form,用来接收参数的,一个简单的NotEmpty注解校验,merchantName这个参数是必传的: pack ...
- 【spring】-- jsr303参数校验器
一.为什么要进行参数校验? 当我们在服务端控制器接受前台数据时,肯定首先要对数据进行参数验证,判断参数是否为空?是否为电话号码?是否为邮箱格式?等等. 这里有个问题要注意: 前端代码一般上会对这些数据 ...
- springmvc请求参数异常统一处理,结合钉钉报告信息定位bug位置
参考之前一篇博客:springmvc请求参数异常统一处理 1.ExceptionHandlerController package com.oy.controller; import java.tex ...
- @Validated和@Valid校验参数、级联属性、List
@Validated和@Valid的区别 在Controller中校验方法参数时,使用@Valid和@Validated并无特殊差异(若不需要分组校验的话): @Valid:标准JSR-303规范的标 ...
随机推荐
- postgresSQL 实现数据修改后,自动更新updated_date/ts等字段
1. 需求说明: 实现MYSQL中有on update CURRENT_TIMESTAMP 2. 需求分析 由于数据库迁移需要将MYSQL中的数据迁移到postgresSQL中,由于MYSQL中有on ...
- django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.
异常汇总:https://www.cnblogs.com/dotnetcrazy/p/9192089.html 这个是Django对MySQLdb版本的限制,我们使用的是PyMySQL,所以不用管它 ...
- TensorFlow 辨异 —— tf.placeholder 与 tf.Variable
https://blog.csdn.net/lanchunhui/article/details/61712830 https://www.cnblogs.com/silence-tommy/p/70 ...
- Ubuntu18.04关机卡死问题
直接进入正题!你的电脑卡死说明带有独显!而Ubuntu默认是不给你的显卡装驱动的,那这就导致关机卡死的问题.按住键盘Ctrl+Alt+T打开终端,输入下面的命令 software-properties ...
- Java基础--面向对象编程3(继承)
1.继承的作用 为了提取两个类中公共的代码,可以使用继承抽取重复性的代码到一个公共类中. 这个公共的类称为父类(super class),继承于父类的类称为子类(sub class). 2.java继 ...
- MySQL实战45讲学习笔记:索引(第五讲)
一.需要回表的案例 在下面表T中,执行下面语句,需要执行几次树的搜索操作?会扫描多少行? select * from T where k between 3 and 5 1.初始化语句 mysql&g ...
- Python——Python+Pydev出现SyntaxError: Non-UTF-8 code
搭建好Python+Pydev后发现每次输入中文,包括注释,会出现语法错误提示,如: SyntaxError: Non-UTF-8 code starting with... 可通过下面方法解决. 1 ...
- NIPS2017-The neural hawks process
NIPS2017哪些论文值得关注 论文链接 1.首先这篇文章研究的是 event stream,什么是event stream呢 ? 假如你是一个医生,你每天会看到很多病人 ,对于每一个病人,你都有他 ...
- Java SE之快速失败(Fast-Fail)与快速安全(Fast-Safe)的区别[集合与多线程/增强For](彻底详解)
声明 特点:基于JDK源码进行分析. 研究费时费力,如需转载或摘要,请显著处注明出处,以尊重劳动研究成果:博客园 - https://www.cnblogs.com/johnnyzen/p/10547 ...
- sqli注入--利用information_schema配合双查询报错注入
目录 sqli-labs 5.6双查询报错注入通关 0x01 获取目标库名 0x02 获取库中表的数量 0x03 获取库中表名 0x04 获取目标表中的列数 0x05 获取目标表的列名 0x06 从列 ...