【问题标题】:How to unwrap Custom RuntimeException from Json Mapping Exception如何从 Json 映射异常中解开自定义 RuntimeException
【发布时间】:2019-10-23 14:41:24
【问题描述】:

在 spring 数据休息项目中,我使用自定义 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);
        }
    }
}

我的用户.class

@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

我是不是错过了什么!

【问题讨论】:

    标签: jackson spring-data-rest json-deserialization runtimeexception


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-08
      • 1970-01-01
      • 2016-06-10
      • 2011-07-18
      • 2021-12-02
      • 1970-01-01
      • 2022-11-21
      • 2015-10-07
      相关资源
      最近更新 更多