Initialize exception with stacktrace from another exception?

﹥>﹥吖頭↗ 提交于 2019-12-10 18:27:34

问题


I have client-server system. They communicate via RMI, so serialization/deserialization is involved. Server sends a response to client upon a request. If exception occurs it is set in the response.

However, if some exception occurs at the server and the client does not know about it. So I need to wrap the original exception but to keep the stacktrace for debug purposes. Is there more elegant solution?

//response from server to client
class Response {
    private MyException e;

    public void set(MyException e) {
       this.e = e;
    }
}

//some other code
catch (MyException e) {
   response.set(e);      
} catch (Exception e) {
   //could be exception which does not exist at client
   //so I can not just set because it would cause ClassNotFoundException at client
   response.set(new MyException(e.getMessage() + ": " + e.getStackTrace()));   
}

It seems that API supports only setting cause which I cannot because of the problem abovementioned. Can I set a stacktrace from another exception without setting cause?


回答1:


You might consider the method setStackTrace(), for example:

Throwable originalException = ...;
Throwable clientException = ...;
clientException.setStackTrace(originalException.getStackTrace());

The stacktrace elements themselves appear to consist of strings only, so this should not present a problem for the client which does not know about special server classes.



来源:https://stackoverflow.com/questions/24140634/initialize-exception-with-stacktrace-from-another-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!