gpt4 book ai didi

java - 尝试将异常对象转换为 Json 文本时出现异常

转载 作者:行者123 更新时间:2023-11-30 09:28:25 26 4
gpt4 key购买 nike

我遇到了这个异常

Caused by: java.lang.StackOverflowError
at java.util.ArrayList.get(ArrayList.java:322)[:1.6.0_12]
at com.google.gson.stream.JsonWriter.peek(JsonWriter.java:354)

当尝试将异常对象转换为 Json 文本时,如下代码

Exception exception = new Exception("Test");    
String gsonText = gson.toJson(exception);

最佳答案

你得到一个 StackOverflowError 因为异常的 cause 实例成员变量被初始化为它自己。序列化程序尝试遍历对象但永远不会完成,因为它一直遵循对原因的引用。

有一个 message on the GSON google group describing this problem ,建议的解决方案是:

So, you have three (exclusive) choices:

1) If you are serializing your own exceptions, modify all of your exceptions to set the cause to null, or to passed parameter upon constructing.

2) Call initCause(null) on any exceptions returning (null) from getCause() (may end up getting some IllegalStateExceptions here)

3) Write your own Serializer that would call getCause() rather than attempting to dereference "cause" field.

Also, attempting to send serialized exception code over the wire may be somewhat of a unorthodox design choice.

通常给应用程序开发人员的建议是不要向客户端显示堆栈跟踪,因此我建议在异常时调用 toString 或以其他方式将异常映射到服务器端的消息并发送消息。

关于java - 尝试将异常对象转换为 Json 文本时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14040965/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com