如何统一处理Spring Boot中请求体与路径参数的校验异常?
统一处理Spring WebFlux校验异常返回格式
在使用spring-boot-starter-validation(Spring Boot 2.7.2 + WebFlux)时,请求体校验会抛出WebExchangeBindException,路径/查询参数校验会抛出ConstraintViolationException,可通过全局异常处理器统一捕获两类异常,返回包含所有校验错误的统一格式响应。
实现方案
创建全局异常处理类,分别捕获两类异常并提取错误信息,最终返回结构一致的Map响应:
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.bind.support.WebExchangeBindException; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import java.util.HashMap; import java.util.Map; @RestControllerAdvice public class GlobalValidationExceptionHandler { // 捕获请求体校验异常 @ExceptionHandler(WebExchangeBindException.class) public ResponseEntity<Map<String, String>> handleRequestBodyValidation(WebExchangeBindException ex) { Map<String, String> errorMap = new HashMap<>(); ex.getBindingResult().getAllErrors().forEach(error -> { String field = ((FieldError) error).getField(); errorMap.put(field, error.getDefaultMessage()); }); return new ResponseEntity<>(errorMap, HttpStatus.BAD_REQUEST); } // 捕获路径/查询参数校验异常 @ExceptionHandler(ConstraintViolationException.class) public ResponseEntity<Map<String, String>> handleParamValidation(ConstraintViolationException ex) { Map<String, String> errorMap = new HashMap<>(); ex.getConstraintViolations().forEach(violation -> { // 从属性路径中提取字段名(格式为"方法名.字段名",取后半部分) String field = violation.getPropertyPath().toString().split("\\.")[1]; errorMap.put(field, violation.getMessage()); }); return new ResponseEntity<>(errorMap, HttpStatus.BAD_REQUEST); } }
关键说明
@RestControllerAdvice:标记类为全局异常处理器,自动作用于所有WebFlux控制器WebExchangeBindException处理:从BindingResult中获取请求体字段的校验错误,提取字段名和错误提示ConstraintViolationException处理:从ConstraintViolation中解析属性路径,拆分出实际字段名(如control.mark),并提取错误提示- 统一响应格式:两类异常处理均返回
Map<String, String>结构,键为字段名,值为错误信息,HTTP状态码统一为400(Bad Request)
配置完成后,当请求同时存在请求体错误和路径/查询参数错误时,会返回合并所有错误信息的响应体,与期望格式一致。
内容的提问来源于stack exchange,提问作者Pierre Recuay
相关产品推荐
相关产品推荐

