FasterXML / jackson-annotations

Core annotations (annotations that only depend on jackson-core) for Jackson data processor
https://github.com/FasterXML/jackson
Apache License 2.0
1.03k stars 330 forks source link

FEATURE: annotation to throw custom exception when std object deserialization fails #130

Closed fabienrenaud closed 4 years ago

fabienrenaud commented 6 years ago

I can't find an annotation to tell jackson to throw a custom exception automatically when an object deserialization (or serialization?) fails. Jackson throws its default exception and that is good enough most of the time. But occasionally, more granularity than the JsonParseException is needed to trigger the appropriate error flows. It is possible to throw custom exceptions either by implementing custom serializers/deserializers or by throwing an exception from the JsonCreator constructor but that typically requires adding boiler plate code mimicking what jackson already does well.

For example, say I have an http request that has a type and subtype enums in its payload. If the deserialization of either does not match any know enum values, the request should fail and the web app should return a 400 with a summary of why the request is invalid (which I don't expect jackson to provide in full). With custom exceptions thrown by each enum, this is easy to handle at the higher level (e.g: in the spring exception mapper).

@JsonOnDeserializeError(throw = RequestTypeException.class)
enum RequestType {
   FOO,
   BAR
}

@JsonOnDeserializeError(throw = RequestSubTypeException.class)
enum RequestSubType {
   APPLE,
   ORANGE
}

This annotation could also be extended to prevent some object deserialization failures to fail the entire payload deserialization (e.g: some enum/objects okay to fail deserialization and be set to a default value; but default behavior should throw the generic parse exception).

cowtowncoder commented 6 years ago

Existing web frameworks offer such functionality on endpoints already don't they?

fabienrenaud commented 6 years ago

The example I gave is for a web app but the need to identify precisely which object failed deserialization is broader. Moreover, I do not believe web frameworks support introspecting the json payload and identifying which parts jackson fails to deserialize...

cowtowncoder commented 4 years ago

At this point I do not think this is something I want to pursue; I am not convinced this is something Jackson should do.