If you are writing a web service using Java and deploying it in Axis2, you need to follow the steps below to propagate the exception properly to the client side.
Let’s say you have an exception you want to throw with a respective error message. Your method would look something like;
public String foo throws MyException { if (true) { throw new MyException("This is my exception"); } }
If you codegen your axis2 client stub you will see that the exception will be thrown when using the client. But if you catch that exception and print out the message, you will notice that the message is lost.
try { String s = client.foo(); } catch (MyExceptionException e) { // the codegen exception thrown System.out.println("The error that occurred is : " + e.getMessage()); }
This will output something like;
The error that occurred is : MyException
To preserve the exception message, we need to include it as an attribute just like we would do in a bean class. Here’s an example of the MyException class;
public class MyException extends Exception { private String message; public MyException(String s, Throwable throwable) { super(s, throwable); this.message = s; } public MyException(String s) { super(s); this.message = s; } @Override public String getMessage() { return this.message; } }
This can of course be extended to send any number of arbitrary attributes with the exception, given that they are web service friendly.
Now, you need to codegen your client and modify the client code as follows:
try { String s = client.foo(); } catch (MyExceptionException e) { System.out.println("The error that occurred is : " + e.getFaultMessage().getMyException().getMessage()); }
When you run the code, the output will be as follows:
The error that occurred is : This is my exception