spring-mvc - 如何处理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 这样的日期”。
解决方案
一种可能是使用@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());
}
推荐阅读
- erlang - Erlang 中是否有可用的模块来查找无向图的所有循环?
- java - 将休眠事件记录在与标准输出控制台附加程序不同的文件中
- snowflake-cloud-data-platform - Snowflake SCIM 错误“指定的组成员资格值无效”
- php - 省略包控制器的 `redirect()->action()` 方法的默认控制器命名空间
- qt - 设置弹出高度以包含内容
- typescript - 从 Firebase Cloud Function 调用 Google Books API 时出现 500 错误
- java - 无法使用 scala 解密 OpenSSL 生成的私钥
- performance - 连续调用 fortran 中的同一子例程,性能显着降低
- javascript - 场景光标中断 raycaster
- java - 我无法打开 jar 文件