springboot中@Valid注解抛出异常的处理@Valid实体类中注解的异常抛出处理
实体类中的写法
/**
* ⼿机号
*/
@NotNull(message = "⼿机号不能为空")
@Pattern(regexp = "^[1][3,4,5,6,7,8,9][0-9]{9}$", message = "⼿机号格式有误")
String phone;
异常处理的类
@ControllerAdvice
@ResponBody
public class GlobleExceptionHandler {
/**
* 要拦截的异常Exception
*/
@ExceptionHandler(value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class}) public ResponEntity<Result<?>> handleValidatedException(Exception e) {
Result<?> resp = null;
if (e instanceof MethodArgumentNotValidException) {
// BeanValidation exception
MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
resp = (500, ex.getBindingResult().getAllErrors().stream()
.map(ObjectError::getDefaultMessage)
.collect(Collectors.joining("; "))
);
} el if (e instanceof ConstraintViolationException) {
// BeanValidation GET simple param
ConstraintViolationException ex = (ConstraintViolationException) e;
resp = (500,
.map(ConstraintViolation::getMessage)
.collect(Collectors.joining("; "))
);
} el if (e instanceof BindException) {
// BeanValidation GET object param
BindException ex = (BindException) e;
resp = (500,
.map(ObjectError::getDefaultMessage)
.collect(Collectors.joining("; "))
);
}
return new ResponEntity<>(resp,HttpStatus.INTERNAL_SERVER_ERROR);
}
}
引⼊的import
api.vo.Result;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
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.ResponBody;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
l.bind.ValidationException;
import java.util.stream.Collectors;
因为异常有可能⾛到
MethodArgumentNotValidException ConstraintViolationException
BindException
这三个其中的任意⼀个
最后返回前端的值是
INTERNAL_SERVER_ERROR(500, “Internal Server Error”),