简体   繁体   中英

What kind of exception to manually throw from an Axis web service?

I have some webservices that are developed on axis 1.1, and I need to make a few changes. During this I am fixing up the exception handling code, but I don't know what kind of exception I should throw when there is an error.

I only need to send the message to the client, I don't need to worry about stack traces and custom information in the exceptions. I don't want to deal with extending soapfaults, or providing reasons for the failures, and all that jazz.

@WebMethod
public string[] myMethod() throws ..?.. {
    throw new AxisFault(); // not recommended
    throw new SOAPFaultException();  // seems overly general
    throw new Exception(); // what we have now
}

Is there any right way to do this, or is throw new Exception the right way to go about it?

You may create a custom exception (say FooException ) extending Exception annotated with JAX-WS @WebFault .

@WebFault(faultBean = "org.foo.bar.FooFault")
public class FooException extends Exception {
    private FooFault fooFault;

    public FooException() {
        super();
    }

    public FooException(String message, FooFault fooFault, Throwable cause) {
        super(message, cause);
        this.fooFault = fooFault;
    }

    public FooException(String message, FooFault fooFault) {
        super(message);
        this.fooFault = fooFault;
    }

    public FooFault getFaultInfo() {
        return fooFault;
    }
}

// this is org.foo.bar.FooFault
public class FooFault {
    // POJO
}

And then you declare that your web method throws that exception.

@WebMethod
public string[] myMethod() throws FooException {
    // do some stuff
    throw new FooException();
    // or with a cause
    try { 
        // something dangerous
    } catch (Exception e) {
        throw new FooException("Shit happens", new FooFault(), e);
    }
    // or like this
    throw new FooException("Foo", new FooFault());
}

JAX-WS should do the rest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM