当项目中使用 @Valid 对表单进行校验,对Integer 类型校验的最小值、最大值等都无法避免对该类型输入字符串的错误提示,即向前端返回数字转化异常的明文代码,对用户的显示特别不友好。
通过设置全局异常捕获机制,将 BindException进行捕获,若异常类型为数字转化异常,即提示该字段格式不正确。
@ExceptionHandler(value = ConstraintViolationException.class)
public ServerResponse ConstraintViolationExceptionHandler(ConstraintViolationException ex) {
List<String> msgList = ex.getConstraintViolations()
.stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.toList());
return ServerResponse.createByErrorMessage(msgList.toString());
}
@ExceptionHandler(value = BindException.class)
public ServerResponse BindExceptionHandler(BindException ex) {
String msgList = ex.getFieldErrors()
.stream()
.map(fieldError -> {
Field field = ReflectionUtils.findField(FieldError.class, "source");
field.setAccessible(true);
Object source = ReflectionUtils.getField(field, fieldError);
if (source instanceof TypeMismatchException) {
TypeMismatchException mismatchException = (TypeMismatchException) source;
source = mismatchException.getPropertyChangeEvent().getSource();
if (mismatchException.getCause() instanceof NumberFormatException) {
field = ReflectionUtils.findField(source.getClass(), fieldError.getField());
ApiModelProperty apiModelProperty = field.getAnnotation(ApiModelProperty.class);
return apiModelProperty == null?"":apiModelProperty.value() + "格式不正确";
}
}
return fieldError.getDefaultMessage();
}
).collect(Collectors.joining("、","您填写的信息共有"+ex.getFieldErrors().size()+"项错误:",""));
return ServerResponse.createByErrorMessage(msgList);
}