如何在springmvc中处理日期绑定失败异常?

问题描述 投票:0回答:1
    @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个回答
0
投票

可能是使用@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());
}
© www.soinside.com 2019 - 2024. All rights reserved.