diff --git a/continew-common/src/main/java/top/continew/admin/common/config/exception/GlobalExceptionHandler.java b/continew-common/src/main/java/top/continew/admin/common/config/exception/GlobalExceptionHandler.java index b7862c6f..e1bfbcd7 100644 --- a/continew-common/src/main/java/top/continew/admin/common/config/exception/GlobalExceptionHandler.java +++ b/continew-common/src/main/java/top/continew/admin/common/config/exception/GlobalExceptionHandler.java @@ -25,6 +25,7 @@ import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; @@ -34,8 +35,11 @@ import org.springframework.web.servlet.NoHandlerFoundException; import top.continew.starter.core.exception.BadRequestException; import top.continew.starter.core.exception.BaseException; import top.continew.starter.core.exception.BusinessException; +import top.continew.starter.core.util.ExceptionUtils; import top.continew.starter.web.model.R; +import java.util.Objects; + /** * 全局异常处理器 * @@ -48,7 +52,6 @@ import top.continew.starter.web.model.R; @RestControllerAdvice public class GlobalExceptionHandler { - /** * 自定义基类异常 */ @@ -92,6 +95,20 @@ public class GlobalExceptionHandler { return R.fail(String.valueOf(HttpStatus.BAD_REQUEST.value()), "参数 '%s' 缺失".formatted(e.getParameterName())); } + /** + * 方法参数无效异常 + *

+ * {@code @NotBlank}、{@code @NotNull} 等参数验证不通过 + *

+ */ + @ExceptionHandler(MethodArgumentNotValidException.class) + public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) { + log.error("[{}] {}", request.getMethod(), request.getRequestURI(), e); + String errorMsg = ExceptionUtils.exToNull(() -> Objects.requireNonNull(e.getBindingResult().getFieldError()) + .getDefaultMessage()); + return R.fail(String.valueOf(HttpStatus.BAD_REQUEST.value()), errorMsg); + } + /** * 方法参数类型不匹配异常 *