When the WSDL service definition includes one or more Faults, the Axis2 WSDL2Java tool creates a separate exception class for each Fault. The JiBX extension to WSDL2Java looks for a mapping definition that relates the element name used for the Fault message in the WSDL to a particular class (essentially using a wrapped approach for Faults, even when unwrapping the actual service operations). The exception class generated by WSDL2Java then has a "message" property that matches the mapped class, and when you create an instance of the exception you must also create the actual message instance and set the message on the exception before it is thrown.
Sound confusing? It can be, so I'll show all the pieces involved in the Fault handling from the
example I've provided. In the case of this example here are the relevant snippets of the WSDL:
<wsdl:types> <schema ...> ... <element name="addDuplicate">
<complexType>
<sequence>
<element name="book" type="tns:BookInformation"/>
</sequence>
</complexType>
</element> </schema> ... </wsdl:types> ... <wsdl:message name="addDuplicateFault">
<wsdl:part element="wns:addDuplicate" name="fault"/>
</wsdl:message>
This says that the Fault message consists of information about a book. To hook this into the JiBX binding I created a bean-style class with standard naming conventions:
package com.sosnoski.ws.library.jibx;public class AddDuplicateFault
{
private Book m_book; public AddDuplicateFault() {} public AddDuplicateFault(Book book) {
m_book = book;
} public void setBook(Book book) {
m_book = book;
} public Book getBook() {
return m_book;
}
}
I then mapped this class to the Fault messgae element in the JiBX binding (
wsdl-binding.xml):
<binding xmlns:tns="http://ws.sosnoski.com/library/types"> <namespace uri="http://ws.sosnoski.com/library/wsdl" prefix="ws"
default="elements"/> <mapping name="addDuplicate"
class="com.sosnoski.ws.library.jibx.AddDuplicateFault">
<structure name="book" field="m_book" map-as="tns:BookInformation"/>
</mapping></binding>
When throwing the exception from the service code I set the message data:
AddDuplicateFaultException e =
new AddDuplicateFaultException("Book already present with matching ISBN");
e.setFaultMessage(new AddDuplicateFault(prior));
throw e;
And when catching the exception in the client code I get the message data:
} catch (AddDuplicateFaultException e) {
System.out.println("Failed adding '" + title +
"' with ISBN '" + isbn + "' - matches existing title '" +
e.getFaultMessage().getBook().getTitle() + ''');
}