问题
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