springboot的validation检验和RestControllerAdvice异常处理简要

  1. 首先是validation
  • 引入依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
  • controller,vo标上相应的注解
//controller
 public RespBean doLogin(@Valid LoginVo loginVo){}
//vo
@Data
public class LoginVo {
    @NotNull
    @IsMobile
    private String mobile;
    @NotNull
    private String password;
}
  • 写自定义注解
    @Constraint(validatedBy = {具体验证类的.class} )
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { IsMobileValidator.class})
public @interface IsMobile {
    boolean required() default true;
    // message是违反验证时会报的信息
    String message() default "手机号格式错误";
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default { };
}

-注解的具体验证类(根据此类判断是否验证通过)

	//需要实现ConstraintValidator<annotation,T>,annotation是自定义的注解,T是你所标注注解地方上的字段比如Mobile的具体值,比如前段传过来的手机号为xxx,为字符串类型,然后这里的value就是手机号值。
 public class IsMobileValidator implements ConstraintValidator<IsMobile,String> {
    private boolean required = false;
    @Override
    public void initialize(IsMobile constraintAnnotation) {
        required = true;
    }
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (required){
            return ValidatorUtil.isMobile(value);
        }
        return true;
    }
}
  1. RestControllerAdvice

首先需要一个继承RuntimeException的自定义异常类,可以需要一个属性,抛出异常时可以new GlobalException(),传入参数

@Data
@AllArgsConstructor
@NoArgsConstructor
public class GlobalException extends RuntimeException{
    private RespBeanEnum respBeanEnum;
}

然后需要一个handlcer,根据抛出的异常,返回对应异常的错误给前端

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public RespBean exceptionHandler(Exception e){
        if (e instanceof GlobalException){
            GlobalException ex = (GlobalException) e;
            return RespBean.error(ex.getRespBeanEnum());
        }else if (e instanceof BindException){
            BindException ex = (BindException) e;
            RespBean respBean = RespBean.error(RespBeanEnum.BIND_ERROR);
            respBean.setMsg("参数校验异常"+ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
            return respBean;
        }
        return RespBean.error(RespBeanEnum.ERROR);
    }
}
在Spring Boot中,全局异常处理通常用于捕获并统一处理应用程序中可能出现的各种异常,包括ValidationException。当使用Spring Data REST或手动验证请求时,如果发生数据校验错误,会抛出ValidationException。为了返回这个异常的信息给前端,你可以创建一个自定义的全局异常处理器。 首先,你需要创建一个实现了`HandlerExceptionResolver`接口的类,例如GlobalExceptionHandler: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; @ControllerAdvice public class GlobalExceptionHandler { @Autowired private MessageSource messageSource; @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseBody public ResponseEntity<ValidationResponse> handleValidationException(MethodArgumentNotValidException ex) { ValidationResponse response = new ValidationResponse(); response.setErrors(new ArrayList<>()); for (FieldError error : ex.getBindingResult().getAllErrors()) { response.getErrors().add(error.getDefaultMessage()); } return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); } // 可能还需要处理其他类型的异常... private static class ValidationResponse { private List<String> errors; // getters and setters... } } ``` 在这个例子中,我们创建了一个`ValidationResponse`类,用来封装错误消息。当`MethodArgumentNotValidException`被捕获时,从异常中获取`FieldError`列表,并将默认错误消息添加到响应体中。最后,通过`ResponseEntity`返回一个HTTP 400 Bad Request状态码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值