在jaxws中自定义fault比较绕弯,以下是自定义一个fault的过程。
1 建立web service以及 web method.
@WebService
public interface PersonService {
@WebMethod
public Person getPersonById(String id) throws MyException;
}
2 MyException.里面一定要有一个faultInfo的object.
@WebFault(name = "MyException")
public class MyException extends Exception implements Serializable {
private static final long serialVersionUID = 1L;
private MyFault faultInfo;
public MyException(String s, MyFault faultInfo) {
super(s);
this.faultInfo = faultInfo;
}
public MyFault getFaultInfo() {
return faultInfo;
}
public void setFaultInfo(MyFault faultInfo) {
this.faultInfo = faultInfo;
}
}
3 定义MyFault.
public class MyFault {
private String errMsg;
private int errCode;
public String getErrMsg() {
return errMsg;
}
public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}
public int getErrCode() {
return errCode;
}
public void setErrCode(int errCode) {
this.errCode = errCode;
}
}
4 发布web service. 查看wsdl,可以看到以下内容。
- <message name="MyException">
<part element="tns:MyException" name="fault" />
</message>
- <portType name="PersonService">
- <operation name="getPersonById">
<input message="tns:getPersonById" />
<output message="tns:getPersonByIdResponse" />
<fault message="tns:MyException" name="MyException" />
</operation>
</portType>
<xs:element nillable="true" name="MyException" type="tns:myFault" />
- <xs:complexType name="myFault">
<xs:element name="errCode" type="xs:int" />
<xs:element name="errMsg" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
5 在client验证。
try {
p = ps.getPersonById("exception");
} catch (MyException me) {
MyFault myFault = me.getFaultInfo();
log.log(Level.INFO, "Error ErrCode = "
+ myFault.getErrCode());
log.log(Level.INFO, "Fault ErrMsg = "
+ myFault.getErrMsg());
}
绕了好大一圈,擦汗。
貌似jaxws2.1可以直接map java exception到fault. 有时间可以试一试。