Adding soap faults without changing WSDL file?

2019-09-11 06:41发布

问题:

I would like to add some SOAP Faults to my JAX-WS web service, but I would like not to change content of WSDL schema. As far as I read I would have to use annotation @WebFault to define SOAP Fault and it automatically causes changes in WSDL during next build. Is there any way to use SOAP Faults without changing content of WSDL scheme?

回答1:

When you throw an Exception from your code it will be automatically mapped to a SOAP fault by JAX-WS in the response. There's no need to define a fault in your WSDL.

Using @WebFault or defining a <soap:fault> element in the WSDL file is used to declare that a specific operation might return a custom SOAP fault.

@WebFault will definitely add a <soap:fault> element in the resulting WSDL.

To recap, throwing an Exception will insert a element in the soap response.

Update

Custom faultstring:

The string message that you pass as a parameter to the Exception constructor represents the faultstring element in the <soap:fault>. Example:

throw new Exception("This is the faultstring text");

Resulting fault in the soap response:

<soap:fault>
    <faultcode>soap:Server</faultcode>
    <faultstring>This is the faultstring text</faultstring>
</soap:fault>

Custom faultcode:

I don't think you can change the faultcode with normal Java exceptions. If you really need to do that you can take a look at JAX-WS SOAPFaultException.

Keep in mind that faultcodes are used to indicate the type of error produced, and most of the time you are going to return a Server fault from your webservice.

This are the four existing fault codes in SOAP 1.1 and 1.2:

  • VersionMismatch: Found an invalid namespace for the SOAP Envelope element.
  • MustUnderstand: An immediate child element of the Header element, with the mustUnderstand attribute set to "1", was not understood.
  • Client: The message was incorrectly formed or contained incorrect information.
  • Server: There was a problem with the server so the message could not proceed.

The first three are going to be created by JAX-WS when parsing the SOAP request and unless there's a very specific situation or you are writing your own JAX-WS handlers/interceptors you will not need to return any other faultcode besides 'Server'.

Custom detail:

The <detail> element will be populated with an element representing the Exception. For example if you are throwing a new MyCustomException("custom message") it will be something like this:

<detail>
    <MyCustomException>
        <message>custom message</message>
    </MyCustomException>
</detail>


回答2:

Test your web service using Soap Ui. I just tested mine, using a custom message in the exception and when I see the Response from Soap Ui, I see that the Fault String has my custom Message.