java 将JSON反序列化为Exception对象

5sxhfpxr  于 2023-04-04  发布在  Java
关注(0)|答案(1)|浏览(173)

我正在使用Jackson从JSON反序列化一个Exception对象。下面是一个简化的演示(使用隐式delegating创建器):

throw new ObjectMapper().readValue("\"custom error message\"", Exception.class);

这是可行的,但不幸的是,堆栈跟踪包括导致异常示例化的Jackson帧:

Exception in thread "main" java.lang.Exception: custom error message
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.fasterxml.jackson.databind.introspect.AnnotatedConstructor.call1(AnnotatedConstructor.java:133)
    at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:332)
    at com.fasterxml.jackson.databind.deser.std.StdDeserializer._deserializeFromString(StdDeserializer.java:265)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1495)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:197)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:187)
    at com.fasterxml.jackson.databind.deser.DefaultDeserializationContext.readRootValue(DefaultDeserializationContext.java:323)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4674)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3629)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3597)

有没有一种方法可以清理它,使它看起来像是在抛出它的同一行上创建的?

vuktfyat

vuktfyat1#

您可以使用fillInStackTrace()将堆栈跟踪重置到您抛出的点:

public class Main {
    public static void main(String[] args) throws Exception {
        Exception e = createException();
        e.fillInStackTrace();
        throw e;
    }

    private static Exception createException() {
        return new Exception("my message");
    }
}

产生:

Exception in thread "main" java.lang.Exception: my message
    at org.example.Main.main(Main.java:11)

如果不调用`fillInStackTrace(),则输出为:

Exception in thread "main" java.lang.Exception: my message
    at org.example.Main.createException(Main.java:16)
    at org.example.Main.main(Main.java:10)

相关问题