Spring Boot 3中REST API校验不生效,无法返回自定义提示信息
Spring Boot REST API校验提示不返回问题解决方案
问题描述
REST API的POST和PUT接口在参数校验失败时(比如description字段为空),仅返回Status: 400 Bad Request,无法返回自定义的校验提示信息(如Description is required),但API核心功能运行正常。
解决方案
Spring Boot默认不会将Jakarta Validation的校验错误详情返回给客户端,需要自定义全局异常处理器捕获校验异常,提取错误信息后返回给客户端。
步骤1:创建全局异常处理器类
新建全局异常处理类,捕获MethodArgumentNotValidException(参数校验失败时抛出的异常),提取字段错误信息并返回:
package com.user.springboot3.project.Exception; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.util.HashMap; import java.util.Map; @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) { Map<String, String> errors = new HashMap<>(); ex.getBindingResult().getAllErrors().forEach(error -> { String fieldName = ((FieldError) error).getField(); String errorMessage = error.getDefaultMessage(); errors.put(fieldName, errorMessage); }); return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST); } }
步骤2:(可选)自定义统一错误响应体
如果需要更规范的响应格式,可创建统一错误响应类:
package com.user.springboot3.project.Model; import java.util.List; public class ErrorResponse { private int statusCode; private String message; private List<String> details; public ErrorResponse(int statusCode, String message, List<String> details) { this.statusCode = statusCode; this.message = message; this.details = details; } // 自行补充getter和setter方法 }
修改全局异常处理器的返回逻辑:
@ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<ErrorResponse> handleValidationExceptions(MethodArgumentNotValidException ex) { List<String> details = ex.getBindingResult() .getFieldErrors() .stream() .map(error -> error.getField() + ": " + error.getDefaultMessage()) .toList(); ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), "参数校验失败", details); return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST); }
验证效果
重启应用后,当POST或PUT请求的description字段为空时,接口将返回如下格式的响应:
{ "description": "Description is required" }
(使用自定义错误响应体时,会返回对应的结构化格式)
内容的提问来源于stack exchange,提问作者user23450337
相关产品推荐
相关产品推荐

