问题
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