How to return soapFault in a jax ws web service in JavaEE

The code below is an example of how you can throw a soapFault exception when an error is encountered in your web service  call.

There are basically 2 things 2 take note, see comments in code.


//#1 - inject WebServiceContext
@Resource
private WebServiceContext webServiceContext;

//#2 get the soapMessage, add a soapFault in body and throw the soapFault exception.
SOAPMessageContext jaxwsContext = (SOAPMessageContext) webServiceContext.getMessageContext();
SOAPMessage soapMsg = jaxwsContext.getMessage();
try {
SOAPFault soapFault = soapMsg.getSOAPBody().addFault();
soapFault.setFaultString("ERROR");
Name qname = soapMsg.getSOAPPart().getEnvelope().createName("Client", null, SOAPConstants.URI_NS_SOAP_ENVELOPE);
soapFault.setFaultCode(qname);
throw new SOAPFaultException(soapFault);
} catch (SOAPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

0 nhận xét:

Đăng nhận xét