使用 @exceptionhandler 注解在 @controlleradvice 类中捕获 datetimeexception 或 methodargumenttypemismatchexception。针对 spring boot 默认使用的 jackson 日期解析,需配置 objectmapper 并处理 invalidformatexception;若使用 jsr-310 类型,则直接捕获 datetimeexception。这样可以将具体的解析错误转化为统一的 json 错误响应。

如何统一处理 HTTP 400 参数绑定异常
通过 @ControllerAdvice 结合 @ExceptionHandler(MethodArgumentTypeMismatchException.class) 可以拦截因格式错误导致的参数绑定失败。当请求参数无法转换为预期的日期类型时,Spring MVC 会抛出此异常,我们可以在该方法中返回自定义的错误信息。

import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ResponseEntity<string> handleTypeMismatch(MethodArgumentTypeMismatchException ex) {
String paramName = ex.getName();
String value = ex.getValue() != null ? ex.getValue().toString() : "";
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("Parameter '" + paramName + "' with value '" + value + "' is invalid");
}
}</string>
上述代码定义了一个全局异常处理器。当控制器方法接收到的日期字符串格式不符合预期(例如期望 yyyy-MM-dd 但收到 2023/01/01)时,Spring 会触发 MethodArgumentTypeMismatchException。该处理器提取参数名和错误值,返回一个包含详细信息的 400 状态码响应。这确保了前端能明确知道哪个字段解析失败。
如何处理 Jackson 反序列化日期异常
在使用 REST API 接收 JSON 请求体时,日期字段通常由 Jackson 库进行反序列化。如果 JSON 中的日期格式与 Java 对象定义的格式不匹配,Jackson 会抛出 InvalidFormatException。我们需要在 @ControllerAdvice 中专门捕获这个异常,以提供比默认更友好的错误提示。

import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
@RestControllerAdvice
public class JsonExceptionHandler {
@ExceptionHandler(InvalidFormatException.class)
public ResponseEntity<string> handleInvalidFormat(InvalidFormatException ex) {
String targetType = ex.getTargetType().getSimpleName();
String value = ex.getValue().toString();
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("Cannot parse date value '" + value + "' into " + targetType);
}
}</string>
这段代码专门处理 JSON 反序列化阶段的日期错误。当客户端发送的 JSON 中包含非法格式的日期字符串时,Jackson 无法将其映射到 LocalDateTime 或其他日期类型,从而抛出 InvalidFormatException。处理器捕获该异常后,返回明确的错误描述。这种处理方式与参数绑定异常分离,因为两者发生的阶段不同:前者在请求体读取阶段,后者在参数转换阶段。
基于 LocalDateTime 输入的具体解析问题
当程序输入为 2023-13-01T10:00:00 时,由于月份 13 无效,解析会失败。对于 LocalDateTime 类型,Spring Boot 默认使用 ISO-8601 格式。如果输入不符合该格式或包含非法日期值,将直接导致 DateTimeException。在 @ControllerAdvice 中捕获此类异常可以防止应用崩溃,并返回标准化的错误响应。











