How to make Jackson throw exception as is when deserialization mapping fail
For anyone looking for a different solution, this worked for me on Spring Boot 2.2.8.RELEASE. NB: This is example is when you have a rest controller with request body that is has an enum and clients could send a wrong field string gender and you want to provide proper error message:
@PostMapping
public ResponseEntity<ProfileResponse> updateProfile(@RequestBody @Valid ProfileRequest profileRequest) {
ProfileResponse profile = //do something important here that returns profile object response
return ResponseEntity
.status(HttpStatus.OK)
.body(profile);
}
ProfileRequest looks like
@Data //Lombok getters and setters
public class ProfileRequest{
private GenderEnum gender;
//some more attributes
}
Add this property to the aplication.properties file to make sure that our custom exception GlobalRuntimeException (see later for definition) is not wrapped in JsonMappingException exception.
spring.jackson.deserialization.WRAP_EXCEPTIONS=false
Then create a class which spring boot will auto create a bean for (This will be used for Deserializing the field gender of type enum). If we don't find an the enum, then we know to throw an error.
@JsonComponent
public class GenderEnumDeserializer extends JsonDeserializer<GenderEnum> {
@Override
public GenderEnum deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String val = p.getValueAsString();
GenderEnum genderEnum = GenderEnum.fromName(val);
if(genderEnum == null){
throw new GlobalRuntimeException("Invalid gender provided. Valid values are MALE | FEMALE | OTHER");
}
return genderEnum;
}
}
The "forName" method in GenderEnum looks like below.
public static GenderEnum fromName(String name) {
GenderEnum foundGenderEnum = null;
for (GenderEnum genderEnum : values()) {
if (genderEnum.name().equalsIgnoreCase(name)) {
foundGenderEnum = genderEnum;
}
}
return foundGenderEnum;
}
We would then setup catching the GlobalRuntimeException in our ControllerAdvice:
@ResponseBody
@ExceptionHandler(GlobalRuntimeException.class)
ResponseEntity<?> handleInvalidGlobalRuntimeException(HttpServletRequest request, GlobalRuntimeException ex) {
LOGGER.error("Error " + ex);
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(new ErrorMessage(ex.getCustomMessage));
}
That's it.
Inside of Jackson's StdValueInstantiator
this method gets hit when an exception is thrown during deserialization:
protected JsonMappingException wrapException(Throwable t)
{
while (t.getCause() != null) {
t = t.getCause();
}
if (t instanceof JsonMappingException) {
return (JsonMappingException) t;
}
return new JsonMappingException("Instantiation of "+getValueTypeDesc()+" value failed: "+t.getMessage(), t);
}
As you can see, this will iterate through each "level" of your nested runtime exceptions and set the last one it hits as the cause for the JsonMappingException
it returns.
Here is the code I needed to get this working:
Register a new module to the
ObjectMapper
.@Test public void testJackson() { ObjectMapper jsonMapper = new ObjectMapper(); jsonMapper.registerModule(new MyModule(jsonMapper.getDeserializationConfig())); String json = "{\"id\": \"1\"}"; try { Q q = jsonMapper.readValue(json, Q.class); System.out.println(q.getId()); } catch (JsonMappingException e) { System.out.println(e.getCause()); //java.lang.RuntimeException: ex 2 } catch (JsonParseException e) { } catch (IOException e) { } }
Create a custom module class.
public class MyModule extends SimpleModule { public MyModule(DeserializationConfig deserializationConfig) { super("MyModule", ModuleVersion.instance.version()); addValueInstantiator(Q.class, new MyValueInstantiator(deserializationConfig, Q.class)); addDeserializer(Q.class, new CustomDeserializer()); } }
Create a custom
ValueInstantiator
class to overridewrapException(...)
. Add the instantiator to the module.public class MyValueInstantiator extends StdValueInstantiator { public MyValueInstantiator(DeserializationConfig config, Class<?> valueType) { super(config, valueType); } @Override protected JsonMappingException wrapException(Throwable t) { if (t instanceof JsonMappingException) { return (JsonMappingException) t; } return new JsonMappingException("Instantiation of "+getValueTypeDesc()+" value failed: "+t.getMessage(), t); } }
Create a custom deserializer to get the module to work properly. Add this class to the module initialization as well.
public class CustomDeserializer extends StdScalarDeserializer<Q> { public CustomDeserializer() { super(Q.class); } @Override public Q deserialize(JsonParser jp, DeserializationContext context) throws IOException { JsonNode node = jp.getCodec().readTree(jp); return new Q(node.get("id").asText()); } @Override public Object deserializeWithType(JsonParser jp, DeserializationContext ctxt, TypeDeserializer typeDeserializer) throws IOException { return deserialize(jp, ctxt); } }