|
25 | 25 | import org.springframework.http.HttpStatus; |
26 | 26 | import org.springframework.http.converter.HttpMessageNotReadableException; |
27 | 27 | import org.springframework.web.HttpRequestMethodNotSupportedException; |
| 28 | +import org.springframework.web.bind.MethodArgumentNotValidException; |
28 | 29 | import org.springframework.web.bind.MissingServletRequestParameterException; |
29 | 30 | import org.springframework.web.bind.annotation.ExceptionHandler; |
30 | 31 | import org.springframework.web.bind.annotation.RestControllerAdvice; |
|
34 | 35 | import top.continew.starter.core.exception.BadRequestException; |
35 | 36 | import top.continew.starter.core.exception.BaseException; |
36 | 37 | import top.continew.starter.core.exception.BusinessException; |
| 38 | +import top.continew.starter.core.util.ExceptionUtils; |
37 | 39 | import top.continew.starter.web.model.R; |
38 | 40 |
|
| 41 | +import java.util.Objects; |
| 42 | + |
39 | 43 | /** |
40 | 44 | * 全局异常处理器 |
41 | 45 | * |
|
48 | 52 | @RestControllerAdvice |
49 | 53 | public class GlobalExceptionHandler { |
50 | 54 |
|
51 | | - |
52 | 55 | /** |
53 | 56 | * 自定义基类异常 |
54 | 57 | */ |
@@ -92,6 +95,20 @@ public R handleMethodArgumentTypeMismatchException(MissingServletRequestParamete |
92 | 95 | return R.fail(String.valueOf(HttpStatus.BAD_REQUEST.value()), "参数 '%s' 缺失".formatted(e.getParameterName())); |
93 | 96 | } |
94 | 97 |
|
| 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 | + |
95 | 112 | /** |
96 | 113 | * 方法参数类型不匹配异常 |
97 | 114 | * <p> |
|
0 commit comments