Skip to content

Commit 0726a21

Browse files
committed
feat: GlobalExceptionHandler 增加 MethodArgumentNotValidException 处理(之前使用 Graceful Reponse 托管会存在错误全部返回的问题)
1 parent 798182d commit 0726a21

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

continew-common/src/main/java/top/continew/admin/common/config/exception/GlobalExceptionHandler.java

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import org.springframework.http.HttpStatus;
2626
import org.springframework.http.converter.HttpMessageNotReadableException;
2727
import org.springframework.web.HttpRequestMethodNotSupportedException;
28+
import org.springframework.web.bind.MethodArgumentNotValidException;
2829
import org.springframework.web.bind.MissingServletRequestParameterException;
2930
import org.springframework.web.bind.annotation.ExceptionHandler;
3031
import org.springframework.web.bind.annotation.RestControllerAdvice;
@@ -34,8 +35,11 @@
3435
import top.continew.starter.core.exception.BadRequestException;
3536
import top.continew.starter.core.exception.BaseException;
3637
import top.continew.starter.core.exception.BusinessException;
38+
import top.continew.starter.core.util.ExceptionUtils;
3739
import top.continew.starter.web.model.R;
3840

41+
import java.util.Objects;
42+
3943
/**
4044
* 全局异常处理器
4145
*
@@ -48,7 +52,6 @@
4852
@RestControllerAdvice
4953
public class GlobalExceptionHandler {
5054

51-
5255
/**
5356
* 自定义基类异常
5457
*/
@@ -92,6 +95,20 @@ public R handleMethodArgumentTypeMismatchException(MissingServletRequestParamete
9295
return R.fail(String.valueOf(HttpStatus.BAD_REQUEST.value()), "参数 '%s' 缺失".formatted(e.getParameterName()));
9396
}
9497

98+
/**
99+
* 方法参数无效异常
100+
* <p>
101+
* {@code @NotBlank}、{@code @NotNull} 等参数验证不通过
102+
* </p>
103+
*/
104+
@ExceptionHandler(MethodArgumentNotValidException.class)
105+
public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
106+
log.error("[{}] {}", request.getMethod(), request.getRequestURI(), e);
107+
String errorMsg = ExceptionUtils.exToNull(() -> Objects.requireNonNull(e.getBindingResult().getFieldError())
108+
.getDefaultMessage());
109+
return R.fail(String.valueOf(HttpStatus.BAD_REQUEST.value()), errorMsg);
110+
}
111+
95112
/**
96113
* 方法参数类型不匹配异常
97114
* <p>

0 commit comments

Comments
 (0)