How to unwrap Custom RuntimeException from Json Mapping Exception

偶尔善良 提交于 2020-01-06 05:16:08

问题


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

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

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

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

Have i missed some thing!


回答1:


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


来源:https://stackoverflow.com/questions/58525409/how-to-unwrap-custom-runtimeexception-from-json-mapping-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!