如何从Json映射异常中解包自定义RuntimeException [英] How to unwrap Custom RuntimeException from Json Mapping Exception

查看:266
本文介绍了如何从Json映射异常中解包自定义RuntimeException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在spring数据剩余项目中,我使用自定义RuntimeException在自定义反序列化器中调用

In a spring data rest project i use a custom RuntimeException to be called in a custom Deserializer

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);
        }
    }
}

我的User.class

My User.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

When i send a POST request with a wrong date format the @ControllerAdvice catch the custom RuntimeException

但是当我发送日期格式错误的PATCH请求时,它表明RuntimeException由JsonMappingException包装,而@ControllerAdvice无法捕获 在我设置的属性文件中

But when i send a PATCH request with a wrong date format it seams that the RuntimeException is wrapped by the JsonMappingException and can't be catched by the @ControllerAdvice in the properties file i have set

spring.jackson.deserialization.wrap-exceptions = false

我错过了一些东西!

推荐答案

已解决,的确,日期格式无效的更新请求(补丁/放置)将触发HttpMessageNotReadableException,该请求包装了自定义RuntimeException,在@ControllerAdivce中,覆盖handleHttpMessageNotReadable

Resolved, indeed an update request (patch/put) with an invalid Date format will fire a HttpMessageNotReadableException that wraps the custom RuntimeException, in @ControllerAdivce we have to override 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);
}

这篇关于如何从Json映射异常中解包自定义RuntimeException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆