Spring Boot - REST控制器 - @DateTimeFormat - 无法工作

后端开发 2026-07-12

我有一个Spring Boot应用,其中有一个REST控制器,非常简单:

@GetMapping("/existClaimAfterDate")   
   fun existClaimAfterDate(              
       @RequestParam(
           value = "afterDate",
           required = true
       ) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) afterDate: LocalDate,
   ): Boolean {

我本来期望,当用错误的日期格式调用这个端点时,例如“无效日期”,应该返回HTTP状态码400。

但是现在返回的是500,我看到异常,因为Spring正在解析日期

Caused by: java.time.format.DateTimeParseException: Text 'invalid-date' could not be parsed at index 0
    at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2108)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:2010)
    at java.base/java.time.LocalDate.parse(LocalDate.java:435)
    at org.springframework.format.datetime.standard.TemporalAccessorParser.doParse(TemporalAccessorParser.java:133)
    at org.springframework.format.datetime.standard.TemporalAccessorParser.parse(TemporalAccessorParser.java:92)
    ... 190 common frames omitted

我到底哪里做错了?

解决方案

在你的场景中得到500而不是400,是因为:

它无法将你无效的日期转换为LocalDate,因此抛出DateTimeParseException。通常它会把 @RequestBody的校验错误处理为400;如果没有定义具体的处理器,失败会被视为500。要想获得400状态码,必须通过 @RestControllerAdvice捕获这个MethodArgumentTypeMismatchException

参考这个
https://medium.com/thefreshwrites/exception-handling-spring-boot-rest-api-c2656b575fee

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章