首页 > 解决方案 > 如何从 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

我错过了什么吗!

标签: jacksonspring-data-restjson-deserializationruntimeexception

解决方案


已解决,确实具有无效日期格式的更新请求(补丁/放置)将触发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);
}

推荐阅读