1.添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2.定义全局异常处理器
@ControllerAdvice
public class GlobalExceptHandler {
@ResponseBody
@ExceptionHandler(value = BizException.class)
public BaseResponse<?> bizException(BizException e) {
return new BaseResponse<>(e.getErrorCode());
}
@ResponseBody
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public BaseResponse<?> methodArgumentNotValidException(MethodArgumentNotValidException e) {
System.out.println(e.getMessage());
return new BaseResponse<>(ErrcodeEnum.ERROR);
}
@ResponseBody
@ExceptionHandler(value = ConstraintDeclarationException.class)
public BaseResponse<?> constraintDeclarationException(ConstraintDeclarationException e) {
return null;
}
@ResponseBody
@ExceptionHandler(value = NullPointerException.class)
public BaseResponse<?> nullException(NullPointerException e) {
return new BaseResponse<>(ErrcodeEnum.NULL_POINT);
}
/**
* 异常处理
*/
@ResponseBody
@ExceptionHandler(value = Exception.class)
public BaseResponse<?> exceptionHandler(Exception e) {
if (e instanceof BizException) {
BizException bizException = (BizException) e;
return new BaseResponse<>(bizException.getErrorCode());
} else {
return new BaseResponse<>(ErrcodeEnum.ERROR);
}
}
}
3.使用java原生注解
@NotBlank(message="内容不能为空")
message中可以添加错误信息
抛出的异常为MethodArgumentNotValidException类型,可以自行处理
4.自定义注解
@Documented
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = IsPhoneValidator.class)
public @interface IsPhone {
boolean required() default true;
String message() default "手机号格式不正确";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
注解处理类实现javax.validation ConstraintValidator接口
BizException异常继承ConstraintDeclarationException异常类
抛出的异常如果属于ConstraintDeclarationException异常,则会被直接抛出,否则会转为其他异常,无法被异常处理器BizException捕获
5.不在入参时校验
注入javax.validation Validator接口
校验器可以为false,在业务中处理
校验失败后validate这个set会有值,如果校验全成功,set为空