Search code examples
javaexceptionjax-ws

Using @WebFault for JAX-WS exception handling


I am trying to use the @WebFault annotation and I have a web service that can throw several exceptions such as the following example class MyException1.

Following the examples from http://java.globinch.com/enterprise-java/web-services/jax-ws/jax-ws-exceptions-faults-annotation-exception-and-fault-handling-examples/ I coded each exception like MyException1 and all the MyException[N] classes are similar: they have a private member which is the Fault POJO/bean and constructors.

How can I avoid copy pasting N classes like this which only differ in the class name? I can't define a base class and subclass each exception because they can't inherit the constructors.

@WebFault(name="ServiceFault",targetNamespace="http://somenamespace.com")
public class MyException1 extends Exception {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private ServiceFault fault;

    public MyException1(String message) {
        super(message);
    }

    public ServiceFault getFault() {
        return fault;
    }

    public MyException1() {
        super();
        // TODO Auto-generated constructor stub
    }

    public MyException1(String message, Throwable cause,
            boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
        // TODO Auto-generated constructor stub
    }

    public MyException1(String message, Throwable cause) {
        super(message, cause);
        // TODO Auto-generated constructor stub
    }

    public MyException1(Throwable cause) {
        super(cause);
        // TODO Auto-generated constructor stub
    }

    public MyException1(ServiceFault fault) {
        super(fault.getFaultString());
        this.fault = fault;
    }

    public MyException1(String message, ServiceFault fault) {
        super(message);
        this.fault = fault;
    }

    public MyException1(String message, ServiceFault fault,
            Throwable cause) {
        super(message, cause);
        this.fault = fault;
    }

    public MyException1(String code, String message) {
        super(message);
        this.fault = new ServiceFault();
        this.fault.setFaultCode(code);
        this.fault.setFaultString(message);
    }

}

... and similarly for MyException2, ..., MyExceptionN

Solution

  • Options:-

    1) Either have a parent MyWSException having a ServiceFault POJO extended by child exception classes having names representing exceptions that occur in your service.

    2) Have a generic MyWSException class with details encapsulated in ServiceFault POJO .