ControllerAdvice定义统一异常处理
springboot版本:2.6.13
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
在实体上添加校验注解,例如:
@NotBlank
@NotEmpty
@NotNull
private 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<>();
//初始化方法
@Override
public void initialize(ListValue constraintAnnotation) {
int[] vals = constraintAnnotation.vals();
System.out.println(vals);
for (int val : vals) {
set.add(val);
}
}
//判断是否校验成功
/**
*
* @param integer 需要校验的值
* @param constraintValidatorContext
* @return
*/
@Override
public boolean isValid(Integer integer, ConstraintValidatorContext constraintValidatorContext) {
return set.contains(integer);//判断是否包含
}
}
分组校验:
1、新建组的接口
2、绑定到相应的组
@NotNull(message = "修改必须指定id",groups = {UpdateGroup.class})
@Null(message = "新增不能指定id",groups = {AddGroup.class})
@TableId
private 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);
}
}
原文地址:https://blog.csdn.net/weixin_48247881/article/details/142449883
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!