Spring Boot 3是否默认提供校验/序列化失败400错误统计指标?
Spring Boot 3: 统计未进入Controller的400错误请求指标
默认情况说明
Spring Boot 3的spring-boot-starter-validation和Actuator默认没有单独统计未进入Controller的400错误请求的指标。默认的http.server.requests指标会统计所有HTTP 400响应,但无法区分是前置校验/序列化失败导致的,还是Controller内部手动返回的400。
自定义指标实现方案
你可以通过全局异常处理器结合MeterRegistry来实现这类指标的统计,核心是捕获那些在请求进入Controller之前抛出的异常:
1. 需捕获的异常类型
- JSON序列化/反序列化失败:对应
HttpMessageNotReadableException(比如请求JSON格式错误、类型不匹配) - 请求参数校验失败:
@RequestBody配合@Valid校验失败:抛出MethodArgumentNotValidException@RequestParam/@PathVariable配合校验注解(如@Min)失败:抛出ConstraintViolationException
2. 具体代码实现
import io.micrometer.core.instrument.MeterRegistry; import jakarta.validation.ConstraintViolationException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.http.converter.HttpMessageNotReadableException; @ControllerAdvice public class InvalidRequestMetricsAdvice { private final MeterRegistry meterRegistry; private static final String INVALID_REQUEST_METRIC_NAME = "custom.http.requests.invalid"; public InvalidRequestMetricsAdvice(MeterRegistry meterRegistry) { this.meterRegistry = meterRegistry; } // 处理JSON序列化/反序列化失败 @ExceptionHandler(HttpMessageNotReadableException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ResponseEntity<String> handleJsonParseError(HttpMessageNotReadableException e) { meterRegistry.counter(INVALID_REQUEST_METRIC_NAME, "error_type", "json_serialization").increment(); return ResponseEntity.badRequest().body("Invalid JSON format"); } // 处理@RequestBody的@Valid校验失败 @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ResponseEntity<String> handleRequestBodyValidationError(MethodArgumentNotValidException e) { meterRegistry.counter(INVALID_REQUEST_METRIC_NAME, "error_type", "request_body_validation").increment(); return ResponseEntity.badRequest().body("Request body validation failed"); } // 处理@RequestParam/@PathVariable的校验失败 @ExceptionHandler(ConstraintViolationException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ResponseEntity<String> handleRequestParamValidationError(ConstraintViolationException e) { meterRegistry.counter(INVALID_REQUEST_METRIC_NAME, "error_type", "request_param_validation").increment(); return ResponseEntity.badRequest().body("Request parameter validation failed"); } }
3. 指标查看
启动应用后,访问/actuator/metrics/custom.http.requests.invalid即可查看统计数据,通过error_type标签可以区分不同类型的错误。
注意事项
- 确保已经引入
spring-boot-starter-actuator和spring-boot-starter-validation依赖 - 如果需要更细致的维度(比如请求路径、HTTP方法),可以在counter中添加更多标签
- 上述异常均为请求到达Controller方法前触发的,不会和Controller内部手动抛出的异常处理逻辑混淆
内容的提问来源于stack exchange,提问作者TheJeff
相关产品推荐
相关产品推荐

