當項目中使用 @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);
}