【问题标题】:How to handle date binding fail exception in springmvc?如何处理spring mvc中的日期绑定失败异常?
【发布时间】:2019-03-16 05:45:16
【问题描述】:
    @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-mvc jackson-databind


    【解决方案1】:

    一种可能是使用@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());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-13
      • 2015-09-01
      相关资源
      最近更新 更多