Commit c95f0c152dd6cca5a9fbe40b8b02d1c14fd6bc17

Authored by YunaiV
1 parent 8ccc55d1

【功能优化】全局:增加 methodArgumentNotValidExceptionExceptionHandler 对「组合校验」场景的兼容

yudao-framework/yudao-spring-boot-starter-web/src/main/java/cn/iocoder/yudao/framework/web/core/handler/GlobalExceptionHandler.java
1 1 package cn.iocoder.yudao.framework.web.core.handler;
2 2  
  3 +import cn.hutool.core.collection.CollUtil;
3 4 import cn.hutool.core.exceptions.ExceptionUtil;
4 5 import cn.hutool.core.map.MapUtil;
5 6 import cn.hutool.core.util.ObjUtil;
... ... @@ -27,6 +28,7 @@ import org.springframework.security.access.AccessDeniedException;
27 28 import org.springframework.util.Assert;
28 29 import org.springframework.validation.BindException;
29 30 import org.springframework.validation.FieldError;
  31 +import org.springframework.validation.ObjectError;
30 32 import org.springframework.web.HttpRequestMethodNotSupportedException;
31 33 import org.springframework.web.bind.MethodArgumentNotValidException;
32 34 import org.springframework.web.bind.MissingServletRequestParameterException;
... ... @@ -37,6 +39,7 @@ import org.springframework.web.servlet.NoHandlerFoundException;
37 39 import org.springframework.web.servlet.resource.NoResourceFoundException;
38 40  
39 41 import java.time.LocalDateTime;
  42 +import java.util.List;
40 43 import java.util.Map;
41 44 import java.util.Set;
42 45  
... ... @@ -135,9 +138,23 @@ public class GlobalExceptionHandler {
135 138 @ExceptionHandler(MethodArgumentNotValidException.class)
136 139 public CommonResult<?> methodArgumentNotValidExceptionExceptionHandler(MethodArgumentNotValidException ex) {
137 140 log.warn("[methodArgumentNotValidExceptionExceptionHandler]", ex);
  141 + // 获取 errorMessage
  142 + String errorMessage = null;
138 143 FieldError fieldError = ex.getBindingResult().getFieldError();
139   - assert fieldError != null; // 断言,避免告警
140   - return CommonResult.error(BAD_REQUEST.getCode(), String.format("请求参数不正确:%s", fieldError.getDefaultMessage()));
  144 + if (fieldError == null) {
  145 + // 组合校验,参考自 https://t.zsxq.com/3HVTx
  146 + List<ObjectError> allErrors = ex.getBindingResult().getAllErrors();
  147 + if (CollUtil.isNotEmpty(allErrors)) {
  148 + errorMessage = allErrors.get(0).getDefaultMessage();
  149 + }
  150 + } else {
  151 + errorMessage = fieldError.getDefaultMessage();
  152 + }
  153 + // 转换 CommonResult
  154 + if (StrUtil.isEmpty(errorMessage)) {
  155 + return CommonResult.error(BAD_REQUEST);
  156 + }
  157 + return CommonResult.error(BAD_REQUEST.getCode(), String.format("请求参数不正确:%s", errorMessage));
141 158 }
142 159  
143 160 /**
... ...