Spring Boot & WebFlux 3.1.5请求无效:如何获取具体字段错误信息?
Spring WebFlux 返回请求参数校验的具体错误信息方案
针对你遇到的Spring WebFlux项目中,请求参数不符合Swagger规范时仅返回笼统错误信息的问题,以下是几个可行的解决方案:
方案1:修正WebFlux错误配置项
你之前使用的server.error.include-message是Servlet环境的配置,WebFlux对应的配置前缀是spring.webflux.error,修改配置文件为:
spring: webflux: error: include-message: always include-binding-errors: always
配置生效后,默认的错误响应会自动包含具体的字段校验信息,比如字段类型不匹配、必填项缺失等细节。
方案2:自定义全局异常处理器捕获ServerWebInputException
如果需要自定义错误响应的格式,可以编写全局异常处理器捕获WebFlux参数校验时抛出的ServerWebInputException,从中提取具体错误信息:
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.server.ServerWebInputException; import reactor.core.publisher.Mono; import java.util.HashMap; import java.util.Map; @ControllerAdvice public class GlobalValidationExceptionHandler { @ExceptionHandler(ServerWebInputException.class) public Mono<ResponseEntity<Map<String, Object>>> handleValidationErrors(ServerWebInputException ex) { Map<String, Object> errorResponse = new HashMap<>(); errorResponse.put("type", "about:blank"); errorResponse.put("title", "Bad Request"); errorResponse.put("status", HttpStatus.BAD_REQUEST.value()); errorResponse.put("instance", ex.getRequestPath()); // 提取具体校验错误 StringBuilder detail = new StringBuilder(); if (ex.getBindingResult() != null) { ex.getBindingResult().getAllErrors().forEach(error -> { String field = ((FieldError) error).getField(); String message = error.getDefaultMessage(); detail.append(field).append(": ").append(message).append("; "); }); } errorResponse.put("detail", detail.length() > 0 ? detail.toString().trim() : "Invalid request content."); return Mono.just(new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST)); } }
该处理器会捕获参数校验失败的异常,解析出错误字段和原因,组装成你需要的响应格式返回。
方案3:确保OpenAPI生成的DTO包含校验注解
检查openapi-generator-maven-plugin的配置,确保开启了校验注解生成,这样生成的Java对象才会带有@NotNull、@Pattern、@Min等校验注解,WebFlux才能识别并校验字段:
<plugin> <groupId>org.openapitools</groupId> <artifactId>openapi-generator-maven-plugin</artifactId> <version>6.6.0</version> <!-- 使用合适的版本 --> <executions> <execution> <goals> <goal>generate</goal> </goals> <configuration> <inputSpec>${project.basedir}/src/main/resources/swagger.yaml</inputSpec> <generatorName>spring</generatorName> <configOptions> <useValidation>true</useValidation> <!-- 必须开启此选项 --> <springBootVersion>3.1.0</springBootVersion> <!-- 匹配你的项目版本 --> <interfaceOnly>false</interfaceOnly> </configOptions> </configuration> </execution> </executions> </plugin>
如果未开启useValidation,生成的DTO不会带有校验注解,WebFlux无法进行字段级别的校验,自然不会返回具体错误信息。
内容的提问来源于stack exchange,提问作者Tsvetoslav Tsvetkov
相关产品推荐
相关产品推荐

