1

When I run the following code:

public static void main(String[] args) throws JsonProcessingException {
    Throwable ex = new IllegalArgumentException("something is wrong");
    ObjectMapper objectMapper = new ObjectMapper();
    System.out.println(objectMapper.writeValueAsString(ex));
}

The output to the console will show that the value in the 'cause' field in the Throwable class is null. This is because of circular reference - the class' field is initialized with the value 'this'.

I've figured that @JsonIdentityInfo is what I'm looking for, but Throwable isn't a class that I created, so I need to use a Mixin. The documentation is deprecated. After reading this discussion on GitHub, this is my latest attempt of adding a mixin:

public static void main(String[] args) throws JsonProcessingException {
    Throwable ex = new IllegalArgumentException("something" +
            " wrong");
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.addMixIn(Throwable.class, MyMixn.class);
    System.out.println(objectMapper.writeValueAsString(ex));
}

@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator
        .class, property = "cause")
public static abstract class MyMixn {

}

However, this only adds another 'cause' field to the output with the value 1 (in addition to the previous one, with the null value).

What I want is to simply have the 'cause' field output the simple class name, so I know the cause Exception.

unlimitednzt
  • 1,035
  • 2
  • 16
  • 25
  • I remember having serious headaches in a previous project due to serialization of Throwable and especially with the 'cause' field. Maybe you'll find a nice way to do what you want this time, but personally if I had to do it again I would convert exceptions in my own model classes before serializing / jsonify – Joel Oct 21 '17 at 18:07
  • How would you convert the exceptions? the 'cause' field needs to be able to reference an Exception, which has another 'cause' field that should reference an exception and so on. – unlimitednzt Oct 21 '17 at 18:54
  • I guess at some point you can have arbitrary rules that constrain what you keep. It depends a lot on your use case, it will be different if you just need to pass information about exceptions without using it algorithmically, or if you actually need the exception to be processed after serialization, in which case it might be more complicated – Joel Oct 22 '17 at 17:40

0 Answers0