How to set a faultCode in a SOAPFault?

David picture David · Sep 23, 2012 · Viewed 14.5k times · Source

Why can I set a faulString, but can't I set a custom fault code in a SOAPFault? When I throw the exception, the text "Code X" does not appear in the SoapFaultException. Someone could tell me why? Thanks.

SOAPFault soapFault = SOAPFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL).createFault();
soapFault.setFaultString("String Y")
soapFault.setFaultCode("Code X");

throw new SOAPFaultException(soapFault);

Answer

O. Sanchez picture O. Sanchez · Mar 8, 2017

It is possible to get the fault code in the soap response with the following example:

String faultString = "String Y";
String faultCodeValue = "Code X";
QName faultCode = new QName("nameSpaceURI", faultCodeValue);
SOAPFault soapFault = null;
try {
    soapFault = SOAPFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL).createFault(faultString, faultCode);
    throw new javax.xml.ws.soap.SOAPFaultException(soapFault);
} catch (SOAPException e1) {
    //
}

I get the following soap fault back:

<?xml version="1.0" ?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Body>
        <S:Fault xmlns:ns4="http://www.w3.org/2003/05/soap-envelope" xmlns="">
        <faultcode xmlns:ns0="nameSpaceURI">ns0:Code X</faultcode>
        <faultstring>String Y</faultstring>
        </S:Fault>
    </S:Body>
</S:Envelope>