Spring Boot 2.5.6 校验注解自定义错误消息未在响应中返回如何解决
问题原因
Spring Boot 从2.3版本开始,默认关闭了错误响应中message和binding errors字段的暴露,参数校验触发的MethodArgumentNotValidException被默认异常处理器捕获时,不会将你在@NotNull中定义的自定义消息填充到响应体中,因此只能看到基础的400错误提示。
解决方法
以下提供两种常用解决方案,可根据业务需求选择:
方案1:修改配置直接开启错误字段暴露
如果不需要定制错误响应结构,直接在application.properties中添加如下配置即可:
# 开启错误消息暴露 server.error.include-message=always # 开启绑定校验错误信息暴露 server.error.include-binding-errors=always
如果使用application.yml,配置如下:
server: error: include-message: always include-binding-errors: always
配置完成后重新请求,默认错误响应中就会出现你定义的自定义校验消息。
方案2:自定义全局异常处理器(更灵活,推荐)
如果需要自定义错误响应的结构,推荐通过全局异常处理器统一捕获校验异常,手动提取自定义错误消息组装返回:
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 GlobalValidationExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<Map<String, String>> handleValidationException(MethodArgumentNotValidException e) { Map<String, String> errorMap = new HashMap<>(); // 遍历所有校验错误,提取字段名和对应的自定义错误消息 for (FieldError fieldError : e.getBindingResult().getFieldErrors()) { errorMap.put(fieldError.getField(), fieldError.getDefaultMessage()); } return new ResponseEntity<>(errorMap, HttpStatus.BAD_REQUEST); } }
配置后校验失败的响应示例如下:
{ "name": "Department name can not be empty" }
内容的提问来源于stack exchange,提问作者filip_j
相关产品推荐
相关产品推荐

