feat(web): 添加全局异常处理器支持请求参数验证
- 新增 MethodArgumentNotValidException 处理器,用于处理 @RequestBody + @Valid 校验失败 - 新增 ConstraintViolationException 处理器,用于处理 @RequestParam/@PathVariable 校验失败 - 实现了统一的参数验证错误响应格式 - 添加了详细的字段错误信息提取和返回机制 - 集成了日志记录功能以跟踪验证失败情况 - 更新了项目版本从 1.5.6 到 1.5.7
This commit is contained in:
@ -1,11 +1,16 @@
|
||||
package vip.jcfd.web.config;
|
||||
|
||||
import jakarta.validation.ConstraintViolationException;
|
||||
import jakarta.validation.ValidationException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.validation.FieldError;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.servlet.resource.NoResourceFoundException;
|
||||
import vip.jcfd.common.core.BizException;
|
||||
@ -54,4 +59,38 @@ public class GlobalExceptionHandler {
|
||||
log.error("接口入参校验失败", e);
|
||||
return R.error(e.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理 @RequestBody + @Valid 校验失败
|
||||
*/
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public R<?> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {
|
||||
log.error("接口入参校验失败", ex);
|
||||
BindingResult bindingResult = ex.getBindingResult();
|
||||
|
||||
String msg = bindingResult.getFieldErrors()
|
||||
.stream()
|
||||
.map(err -> err.getField() + ": " + err.getDefaultMessage())
|
||||
.findFirst()
|
||||
.orElse("参数错误");
|
||||
|
||||
return R.error(msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理 @RequestParam / @PathVariable 校验失败
|
||||
*/
|
||||
@ExceptionHandler(ConstraintViolationException.class)
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public R<?> handleConstraintViolation(ConstraintViolationException ex) {
|
||||
log.error("接口入参校验失败", ex);
|
||||
String msg = ex.getConstraintViolations()
|
||||
.stream()
|
||||
.map(v -> v.getPropertyPath() + ": " + v.getMessage())
|
||||
.findFirst()
|
||||
.orElse("参数错误");
|
||||
|
||||
return R.error(msg);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user