使用 @controlleradvice 结合 @exceptionhandler 捕获 httpmessagenotreadableexception,并在方法中通过 getmostspecificcause() 提取具体的 jackson 异常(如 mismatchedinputexception)进行响应。

如何区分不同的 JSON 解析错误类型
在 @ExceptionHandler 中检查异常链,针对字段缺失、类型不匹配或格式错误返回不同的业务状态码。

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<String> handleJsonErrors(HttpMessageNotReadableException ex) {
Throwable cause = ex.getMostSpecificCause();
if (cause instanceof MismatchedInputException) {
return ResponseEntity.badRequest().body("Missing required field");
} else if (cause instanceof InvalidFormatException) {
return ResponseEntity.badRequest().body("Invalid data type");
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Unknown parsing error");
}
}
如何处理嵌套对象中的深层解析异常
当 JSON 结构包含多层嵌套时,Jackson 抛出的异常通常仍为 MismatchedInputException,但可以通过 getPath() 获取精确的出错路径。

import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import java.util.stream.StreamSupport;
// 在 ControllerAdvice 中
if (cause instanceof MismatchedInputException) {
MismatchedInputException mie = (MismatchedInputException) cause;
String path = StreamSupport.stream(mie.getPath().spliterator(), false)
.map(JsonLocation::getFieldName)
.reduce((a, b) -> a + "." + b)
.orElse(cause.getMessage());
return ResponseEntity.badRequest().body("Field missing at: " + path);
}
基于输入参数为空时的具体处理逻辑
当请求体完全为空或仅包含空白字符时,Spring Boot 默认会抛出 HttpMessageNotReadableException,此时 getMostSpecificCause() 可能返回 EOFException 而非标准的 Jackson 异常。


















