jackson - 如何从 Json 映射异常中解开自定义 RuntimeException
问题描述
在春季数据休息项目中,我使用自定义 RuntimeException 在自定义反序列化器中调用
public class LocalDateDeserializer extends StdDeserializer<LocalDate> {
...
@Override
public LocalDate deserialize(JsonParser jsonparser, DeserializationContext context) throws IOException, JsonProcessingException {
String date = jsonparser.getText();
String name = jsonparser.getCurrentName();
try {
return LocalDate.parse(date, DateTimeFormatter.ISO_LOCAL_DATE);
} catch (DateTimeParseException e) {
throw new ApiJacksonException("error on: " + name);
}
}
}
我的用户类
@Data
@NoArgsConstructor
public class User extends Auditing implements Serializable {
private static final long serialVersionUID = 1L;
...
@DateTimeFormat(iso = ISO.DATE)
@JsonFormat(pattern = "yyyy-MM-dd")
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate birthdate;
}
当我发送日期格式错误的 POST 请求时,@ControllerAdvice 会捕获自定义 RuntimeException
但是当我发送一个日期格式错误的 PATCH 请求时,它会显示 RuntimeException 被 JsonMappingException 包装,并且无法被我设置的属性文件中的@ControllerAdvice 捕获
spring.jackson.deserialization.wrap-exceptions = false
我错过了什么吗!
解决方案
已解决,确实具有无效日期格式的更新请求(补丁/放置)将触发HttpMessageNotReadableException
包装自定义 RuntimeException,在 @ControllerAdivce 中我们必须覆盖handleHttpMessageNotReadable
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
if(ex.getCause() instanceof ApiJacksonException) {
// execute custom code...
}
return super.handleHttpMessageNotReadable(ex, headers, status, request);
}
推荐阅读
- mysql - Docker MySQL - 无法从 Spring Boot 应用程序连接到 MySQL 数据库
- python-3.x - 确定系统用户是否在Windows本地存在的正确方法是什么?
- java - 为什么我必须禁用 csrf 令牌才能使用邮递员发布数据?
- asp.net-core - 如何在模型验证中验证非法字段
- android - 如何使用 OSMDroid 检查当前位置和 KML 点之间的距离?
- git - Git推送到一个拥有新分支的分支
- postgresql - 如何从 postgresql 查询中的字节中获取一个字节字符?
- reactjs - 在 Material-UI v4 中为 `Box` 响应设置 m 和 p 的漂亮方法
- android - Android - 未授予 USE_BIOMETRIC
- javascript - Angular中的域名验证器?