feat: GlobalExceptionHandler 增加 MethodArgumentNotValidException 处理(之前使用 Graceful Reponse 托管会存在错误全部返回的问题)

This commit is contained in:
2025-05-17 14:33:35 +08:00
parent 798182d120
commit 0726a21ead

View File

@@ -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()));
}
/**
* 方法参数无效异常
* <p>
* {@code @NotBlank}、{@code @NotNull} 等参数验证不通过
* </p>
*/
@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);
}
/**
* 方法参数类型不匹配异常
* <p>