首页 > 解决方案 > 如何处理springmvc中的日期绑定失败异常?

问题描述

    @PostMapping("/subscribe/add")
    Subscribe add(@RequestBody Subscribe sub) throws BindException {
        return sub;
    }

Subscribe有一个字段:

    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDate subDate;

当我通过无效日期时,例如"abc",我得到HttpMessageNotReadableException异常。我无法从中获得任何有用的消息HttpMessageNotReadableException,可以发送给客户告诉用户“你应该传递一个像 yyyy-MM-dd 这样的日期”。

标签: spring-mvcjackson-databind

解决方案


一种可能是使用@ExceptionHandler 来捕获 HttpMessageNotReadableException 并将其转换为更明确的 HTTP 代码错误和适当的消息

类似的东西

@org.springframework.web.bind.annotation.ExceptionHandler(IllegalArgumentException.class)
public void handleIllegalArgument(HttpServletResponse res, Exception e)
        throws IOException {
    res.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
}

推荐阅读