refactor: 使用 SpEL Validator 优化部分校验场景

This commit is contained in:
2025-07-06 15:10:08 +08:00
parent acfdfce2cc
commit 0d3c1bb2b1
4 changed files with 21 additions and 24 deletions

View File

@@ -21,6 +21,7 @@ import cn.hutool.core.text.CharSequenceUtil;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
@@ -32,13 +33,13 @@ import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.NoHandlerFoundException;
import top.continew.starter.core.constant.StringConstants;
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;
import org.springframework.validation.BindException;
/**
* 全局异常处理器
@@ -96,16 +97,19 @@ public class GlobalExceptionHandler {
}
/**
* 方法参数无效异常
* 参数校验不通过异常
* <p>
* {@code @NotBlank}、{@code @NotNull} 等参数验证不通过
* </p>
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
@ExceptionHandler({BindException.class, MethodArgumentNotValidException.class})
public R handleBindException(BindException e, HttpServletRequest request) {
log.error("[{}] {}", request.getMethod(), request.getRequestURI(), e);
String errorMsg = ExceptionUtils.exToNull(() -> Objects.requireNonNull(e.getBindingResult().getFieldError())
.getDefaultMessage());
String errorMsg = e.getFieldErrors()
.stream()
.findFirst()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.orElse(StringConstants.EMPTY);
return R.fail(String.valueOf(HttpStatus.BAD_REQUEST.value()), errorMsg);
}