我将尝试使用以下代码从Spring WS(java)中的SOAP Web服务捕获异常:
String faultString = "String Y";
String faultCodeValue = "Code X";
QName faultCode = new QName("http://schemas.xmlsoap.org/soap/envelope/", faultCodeValue);
SOAPFault soapFault = null;
soapFault = SOAPFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL).createFault(faultString, faultCode);
throw new SOAPFaultException(soapFault);
但是,我总是像<faultcode>
(<faultcode>SOAP-ENV:Server</faultcode>)
(即使我更改了faultCodeValue
变量中的值):
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Server</faultcode>
<faultstring xml:lang="en">String Y</faultstring>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
有人知道如何在Web服务响应中更改此值吗?
答案 0 :(得分:0)
实际上我无法得到它。你抛出FaultException然后你捕获并创建一些SOAPMessage?没有QName我得到了预期的结果。
SOAPMessage message = MessageFactory.newInstance().createMessage();
SOAPFault fault = message.getSOAPBody().addFault();
fault.setFaultString("Error");
fault.setFaultCode("99");
message.getSOAPBody().appendChild(fault);
message.writeTo(System.out);
回应;
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>99</faultcode>
<faultstring>Error</faultstring>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
答案 1 :(得分:0)
您可以通过多种方式实现这一目标。如果您需要在SOAP响应中返回动态自定义错误代码。请执行以下操作:
在上面声明的类中,覆盖protected SoapFaultDefinition getFaultDefinition(Object endpoint, Exception ex)
方法并按如下方式提供自定义实现:
@Override
protected SoapFaultDefinition getFaultDefinition(Object endpoint, Exception ex) {
String definitionText = "SERVER";
if (ex instanceof ServiceFaultException) {
MyServiceFault serviceFault = ((MyServiceFaultException) ex).getServiceFault();
QName faultCode = new QName("http://schemas.xmlsoap.org/soap/envelope/", serviceFault.getErrorCd());
definitionText = faultCode.toString();
}
SoapFaultDefinitionEditor editor = new SoapFaultDefinitionEditor();
editor.setAsText(definitionText);
return (SoapFaultDefinition) editor.getValue();
}
您可以通过覆盖
向错误响应中添加更多详细信息customizeFault(Object endpoint, Exception ex, SoapFault fault)
这个班级。