编程语言
首页 > 编程语言> > 序列化java.lang.Throwable与堆栈跟踪一起,导致链和相关的堆栈跟踪

序列化java.lang.Throwable与堆栈跟踪一起,导致链和相关的堆栈跟踪

作者:互联网

我正在编写GWT应用程序,在这里我需要使用使用标准Java序列化机制的GWT RPC发送java.lang.Throwable实例(分别具有其原因链和所有堆栈跟踪)(就我而言).

问题是当我从客户端传递以下示例异常时:

java.lang.RuntimeException (message=null, stacktrace A) caused by
java.io.IOException (message="Problems with io", stacktrace B) caused by
java.lang.IllegalStateException (message="Some error text", stacktrace C), cause=null

在服务器上,我得到以下信息:

java.lang.RuntimeException (message="java.io.IOException: Problems with io", stacktrace X) cause=this

其中stacktrace X只是堆栈跟踪,导致此异常在服务器上反序列化的位置,即与原始堆栈跟踪A,B或C无关,因此堆栈跟踪信息与原因链一起丢失.

阅读了很棒的文章7 Tips for Exception Handling in GWT后,我们发现

the stack trace within an exception is transient, and so is lost from client to server (so if you need it on the server side, send it as a separate parameter)

经过一番谷歌搜索后,我得出的结论是完全序列化/反序列化java.lang实例的主题.使用标准Java序列化技术可抛出的对象并不那么受欢迎.实际上,我找不到任何关于如何实现此功能的详细说明的库或博客.

以前有人坚持解决过吗?是否有针对此问题的建议解决方案?

提前致谢!

解决方法:

好的,找到了解决我问题的简单优雅的解决方案:在GWT 2.5.1中,有一个专门为那些需要而设计的类,名为com.google.gwt.core.client.impl.SerializableThrowable,并带有以下JavaDoc:

The emulated Throwable class does not serialize Throwables recursively and does not serialize the stack trace. This class is an alternative, and can be used by writing a custom serializer for the class which contains a Throwable. See LogRecord_CustomFieldSerializer as an example.

因此,解决我的问题的代码段如下:

// client-side
LogServiceAsync logService = GWT.create(LogService.class);

GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() {

    @Override
    public void onUncaughtException(final Throwable ex) {
        // wrapping throwable in SerializableThrowable to preserve 
        // causes and stack traces upon serialization
        SerializableThrowable serializableEx = new SerializableThrowable(ex);
        // sending instance of SerializableThrowable to server
        logService.log(serializableEx, callbackCodeDoesntMatter);
    }
}

// server-side
public class LogServiceServlet extends RemoteServiceServlet implements LogService {

    @Override
    public void log(final SerializableThrowable ex) {
        // getting original instance Throwable with preserved
        // causes and stack traces
        Throwable originalThrowable = ex.getThrowable();
        originalThrowable.printStackTrace();
    }
}

如果以这种方式实现,它将打印正确的堆栈跟踪信息以及正确的原因.

注意在GWT 2.6.0中,com.google.gwt.core.client.impl.SerializableThrowable类已弃用,取而代之的是com.google.gwt.core.shared.SerializableThrowable,它与第一个仅稍有不同,并且应以类似方式工作.

标签:java,serialization,exception,gwt,stack-trace
来源: https://codeday.me/bug/20191012/1902515.html