spring boot 全局异常处理捕获 json 校验异常,核心在于注册 @controlleradvice 并实现 responsebodyadvice 或配置自定义的 httpmessageconverter。默认情况下,jackson 在反序列化阶段抛出的 jsonmappingexception 会被 spring mvc 包装为 httpmessagenotreadableexception。通过拦截该异常,可以提取原始 json 路径和错误原因,将其转换为前端友好的统一响应格式。

如何区分字段级校验与类型转换错误
字段级校验(如 @NotNull)由 Hibernate Validator 触发,抛出 MethodArgumentNotValidException;而 JSON 结构错误或类型不匹配(如期望数字却收到字符串)由 Jackson 抛出,最终表现为 HttpMessageNotReadableException。两者需分别处理。

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.http.converter.HttpMessageNotReadableException;
import com.fasterxml.jackson.databind.JsonMappingException;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<errorresponse> handleJsonParseException(HttpMessageNotReadableException ex) {
Throwable cause = ex.getCause();
String errorMessage = "JSON parsing failed";
if (cause instanceof JsonMappingException) {
JsonMappingException jme = (JsonMappingException) cause;
if (jme.getPath() != null && !jme.getPath().isEmpty()) {
errorMessage = "Invalid value at path: " + jme.getPath().get(jme.getPath().size() - 1).getFieldName();
}
}
ErrorResponse response = new ErrorResponse("PARSE_ERROR", errorMessage);
return ResponseEntity.badRequest().body(response);
}
}</errorresponse>
上述代码展示了如何从 HttpMessageNotReadableException 中提取底层 JsonMappingException 的路径信息。当请求体 JSON 格式错误时,系统返回 400 状态码及具体出错字段。注意:此方法仅覆盖反序列化阶段的错误,不包含业务逻辑校验。
如何自定义 JSON 解析器以增强错误提示
若需更精细控制 JSON 解析行为,可替换默认的 MappingJackson2HttpMessageConverter,注入自定义 ObjectMapper 并设置 DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES 为 false,同时启用 DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY 等特性提升兼容性。
将包含oralBroadcastingList、materialList、bgmInfo等字段的JSON视频素材转换为剪映API可用的自然语言描述,用于生成视频制作指令,包括素材匹配、时间轴计算、字幕同步、特殊效果处理等。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.DeserializationFeature;
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
return mapper;
}
}
配置完成后,Spring Boot 将使用自定义 ObjectMapper 进行 JSON 反序列化。未知属性不再报错,单值数组自动转为列表。结合前文的异常处理器,可实现更健壮的错误反馈机制。建议在生产环境中开启 spring.jackson.deserialization.fail-on-unknown-properties=true 以便快速定位问题。
当 JSON 中嵌套对象缺失必填字段时会发生什么
若请求体中包含嵌套对象且其内部字段违反 @NotNull 等约束,Hibernate Validator 会在参数绑定阶段抛出 MethodArgumentNotValidException,而非 JSON 解析异常。此时应单独注册对该异常的处理器,遍历 BindingResult 获取每个字段的错误详情。










