Wednesday, April 8, 2009

How to: Throw Custom Exception in Jax-ws

There is an excellent article on Faults and exceptions in JAX-WS, however, it doesn’t say how to throw custom exception clearly. Another post mentioned the below information, which I found most useful after google search to solve the problem. Again, it is still not correct solution.

Make the exception look like a normal JAX-WS generated exception.   That
would basically mean defining a JAXB bean for the data that has all the
getter/setters and such for the data and making the exception look like:
@WebFault
public class MyException extends Exception {
     MyFaultInfo faultInfo;
     public MyException(String msg, MyFaultInfo mfi) {
            ...
     }
     public MyFaultInfo getFaultInfo() {
         return faultInfo;
     }
}
That is basically the "JAX-WS" standard way of doing it and would be portable.  
The entire schema for the exception is defined in the JAXB MyFaultInfo bean.

If you look into jax-ws defination of @WebFault, it is basically on the client side, and was automatically generated! There is no point putting them in the server code. I had to admit that the explanation was clear and I write the following code to solve this problem

public class CustomException extends Exception {

private WSStatus faultInfo = null;

public CustomException(String message, WSStatus faultInfo)
{
super(message);
this.faultInfo = faultInfo;
}
public CustomException(String message, WSStatus faultInfo, Throwable cause)
{
super(message,cause);
this.faultInfo = faultInfo;
}

public CustomException(Exception ex)
{
super(ex.getMessage(),ex.getCause());
}

public WSStatus getErrorCode()
{
if(faultInfo==null)
faultInfo = new WSStatus();
return faultInfo;
}
}


Note that the generated code on client side would be something like CustomException_Exception extends Exception, so make sure you catch/throw the right exception.

No comments: