当前位置: 首页 > news >正文

ControllerAdvice定义统一异常处理

springboot版本:2.6.13<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId></dependency>

在实体上添加校验注解,例如:

	@NotBlank@NotEmpty@NotNullprivate String name;

设置自定义校验注解

package com.xdtmall.common.valid;import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;@Documented
//使用什么校验器
@Constraint(validatedBy = { ListValueConstraintValidator.class })
//标注注解能用在什么位置;方法;属性;
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
//校验注解的时机   运行时获取
@Retention(RetentionPolicy.RUNTIME)
public @interface ListValue {String message() default "{javax.validation.constraints.NotBlank.message}";Class<?>[] groups() default {};Class<? extends Payload>[] payload() default {};int[] vals() default {};
}
public class ListValueConstraintValidator implements ConstraintValidator<ListValue,Integer> {private Set<Integer> set =new HashSet<>();//初始化方法@Overridepublic void initialize(ListValue constraintAnnotation) {int[] vals = constraintAnnotation.vals();System.out.println(vals);for (int val : vals) {set.add(val);}}//判断是否校验成功/**** @param integer 需要校验的值* @param constraintValidatorContext* @return*/@Overridepublic boolean isValid(Integer integer, ConstraintValidatorContext constraintValidatorContext) {return set.contains(integer);//判断是否包含}
}

分组校验:
1、新建组的接口
2、绑定到相应的组

	@NotNull(message = "修改必须指定id",groups = {UpdateGroup.class})@Null(message = "新增不能指定id",groups = {AddGroup.class})@TableIdprivate Long brandId;@NotBlank(message = "品牌名不能为空",groups = {AddGroup.class,UpdateGroup.class})private String name;@NotNull(groups = {AddGroup.class})@URL(message = "logo必须是一个合法的url地址",groups = {AddGroup.class,UpdateGroup.class})private String logo;private String descript;@NotNull(groups = {AddGroup.class,UpdateStatusGroup.class})/*使用自定义校验注解*/@ListValue(vals={0,1},groups = {AddGroup.class, UpdateStatusGroup.class})private Integer showStatus;@NotNull(groups = {AddGroup.class})@Pattern(regexp = "^[a-zA-Z]$",message = "检索首字母必须是一个字母",groups = {AddGroup.class, UpdateGroup.class})private String firstLetter;@NotNull(groups = {AddGroup.class})@Min(value = 0,message = "排序必须大于等于0",groups = {AddGroup.class,UpdateGroup.class})private Integer sort;

controller修改成@Validated(绑定的组)

  @RequestMapping("/update")//@RequiresPermissions("product:brand:update")public R update(@Validated(UpdateGroup.class) @RequestBody BrandEntity brand){brandService.updateById(brand);return R.ok();}
@RequestMapping("/update")//@RequiresPermissions("product:brand:update")public R update(@Valid @RequestBody Entity erand, BindingResult bindingResult){if (bindingResult.hasErrors()) {//如果有校验错误,返回第一个校验信息List<ObjectError> allErrors = bindingResult.getAllErrors();System.out.println(allErrors);//将错误信息返回或者抛异常全局处理。}entityService.updateById(brand);return R.ok();}

在controller添加,例如:

@RequestMapping("/update")//@RequiresPermissions("product:brand:update")public R update(@Valid @RequestBody Entity erand, BindingResult bindingResult){if (bindingResult.hasErrors()) {//如果有校验错误,返回第一个校验信息List<ObjectError> allErrors = bindingResult.getAllErrors();System.out.println(allErrors);//将错误信息返回或者抛异常全局处理。}entityService.updateById(brand);return R.ok();}

使用@RestControllerAdvice统一处理异常信息

@RestControllerAdvice
@Slf4j
public class productExceptionControllerAdvice {@ExceptionHandler(Exception.class)public R handleValidException(MethodArgumentNotValidException e) {log.error("数据效验出现问题{},异常类型{}",e.getMessage(),e.getClass());BindingResult bindingResult = e.getBindingResult();Map<String,String> errMap = new HashMap<>();bindingResult.getFieldErrors().forEach((fieldError) -> {errMap.put(fieldError.getField(),fieldError.getDefaultMessage());});return R.error("校验异常").put("data",errMap);}
}

相关文章:

  • 【力扣 | SQL题 | 每日三题】力扣175, 176, 181
  • CloudMusic:免费听歌
  • python功能测试
  • Tableau|一入门
  • error -- unsupported GNU version gcc later than 10 are not supported;(gcc、g++)
  • 网络编程(6)——发送的时序性,全双工通信
  • 一个 Java 语言简化处理 PDF 的框架,提供了一套简单易用的 API 接口,满足多样化需求又能简化开发流程的处理方案(附教程)
  • 【AD那些事 10 】焊盘如何修改为自己想要的形状!!!!! 焊盘设计规则如何更改??????
  • 【架构设计】同步与异步:应用场景与选择指南
  • cpu路、核、线程、主频、缓存
  • 相似度度量方法有哪些?
  • 数据结构--单链表
  • 创建Express后端项目
  • python之装饰器、迭代器、生成器
  • linux ip命令使用
  • CSS 专业技巧
  • JAVA 学习IO流
  • JavaScript 奇技淫巧
  • JS基础之数据类型、对象、原型、原型链、继承
  • node入门
  • PHP的类修饰符与访问修饰符
  • 类orAPI - 收藏集 - 掘金
  • 我建了一个叫Hello World的项目
  • 用简单代码看卷积组块发展
  • 再次简单明了总结flex布局,一看就懂...
  • 终端用户监控:真实用户监控还是模拟监控?
  • ​LeetCode解法汇总307. 区域和检索 - 数组可修改
  • # MySQL server 层和存储引擎层是怎么交互数据的?
  • #LLM入门|Prompt#2.3_对查询任务进行分类|意图分析_Classification
  • #QT(TCP网络编程-服务端)
  • #Z2294. 打印树的直径
  • (10)ATF MMU转换表
  • (14)学习笔记:动手深度学习(Pytorch神经网络基础)
  • (2024,RWKV-5/6,RNN,矩阵值注意力状态,数据依赖线性插值,LoRA,多语言分词器)Eagle 和 Finch
  • (52)只出现一次的数字III
  • (6) 深入探索Python-Pandas库的核心数据结构:DataFrame全面解析
  • (k8s)kubernetes 部署Promehteus学习之路
  • (Python第六天)文件处理
  • (void) (_x == _y)的作用
  • (多级缓存)缓存同步
  • (二)PySpark3:SparkSQL编程
  • (三)Pytorch快速搭建卷积神经网络模型实现手写数字识别(代码+详细注解)
  • (深度全面解析)ChatGPT的重大更新给创业者带来了哪些红利机会
  • (实战)静默dbca安装创建数据库 --参数说明+举例
  • (转)Google的Objective-C编码规范
  • (总结)(2)编译ORB_SLAM2遇到的错误
  • ****** 二 ******、软设笔记【数据结构】-KMP算法、树、二叉树
  • .net framework4与其client profile版本的区别
  • .NET 中 GetProcess 相关方法的性能
  • .NetCore 如何动态路由
  • .netcore 如何获取系统中所有session_如何把百度推广中获取的线索(基木鱼,电话,百度商桥等)同步到企业微信或者企业CRM等企业营销系统中...
  • @antv/g6 业务场景:流程图
  • @font-face 用字体画图标
  • [] 与 [[]], -gt 与 > 的比较
  • [20170713] 无法访问SQL Server