spring boot 全局异常处理可以通过在 @controlleradvice 中定义针对 httpmessagenotreadableexception 的处理器来捕获编码转换异常。当请求体内容无法被反序列化器正确解析时,框架会抛出此异常,此时只需在自定义的全局异常处理器中拦截该类型并返回统一的错误响应即可。

如何配置全局异常处理器拦截反序列化错误
要拦截此类异常,需要创建一个继承自 ResponseEntityExceptionHandler 或仅使用 @RestControllerAdvice 注解的类。在该类中编写一个方法,使用 @ExceptionHandler(HttpMessageNotReadableException.class) 进行标注。当 Spring MVC 发现请求体的 JSON 格式错误或字符集不匹配导致读取失败时,会自动调用该方法。建议在方法内部记录日志,并返回包含错误信息的 Result 对象。

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;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<result> handleBadRequest(HttpMessageNotReadableException ex) {
// 记录异常信息
System.out.println("Request body parsing failed: " + ex.getMessage());
return ResponseEntity.badRequest().body(Result.error(400, "Invalid request format"));
}
}</result>
如何处理具体的参数绑定失败场景
除了通用的反序列化错误,有时具体的字段类型转换失败(如将字符串转为整数)也会触发类似的机制,通常表现为 MethodArgumentTypeMismatchException 或嵌套在 HttpMessageNotReadableException 中。为了更精细地控制,可以在上述处理器中检查异常的 Cause。如果 Cause 是 InvalidFormatException,则说明是特定字段的值不符合预期类型。通过判断异常链中的具体原因,可以返回更具针对性的错误提示,例如指出哪个字段格式错误。

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.exc.InvalidFormatException;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<result> handleBadRequest(HttpMessageNotReadableException ex) {
Throwable cause = ex.getCause();
if (cause instanceof InvalidFormatException) {
InvalidFormatException ife = (InvalidFormatException) cause;
String fieldName = ife.getPath().get(0).getFieldName();
return ResponseEntity.badRequest().body(Result.error(400, "Field '" + fieldName + "' has invalid type"));
}
return ResponseEntity.badRequest().body(Result.error(400, "General parsing error"));
}
}</result>
当请求头缺少 Content-Type 时会发生什么
如果客户端发送 POST 请求时未指定 Content-Type 为 application/json,或者指定的字符集与 Jackson 默认期望的不一致且未正确配置,Spring Boot 可能无法找到合适的消息转换器。这会导致 HttpMediaTypeNotSupportedException 而非 HttpMessageNotReadableException。因此,确保请求头正确设置是避免编码转换异常的前提。若确实发生了因字符集导致的乱码或解析失败,检查 MappingJackson2HttpMessageConverter 的配置以及客户端发送的实际字节流至关重要。











