how to parse the exception message from the method in the backend to the SOAP response message using JAX-WS?
I am trying to expose one method as webservice from backend using JAX-WS with Tomcat. The backend method is something like below (in CompanyFacade class):
public Company findCompanyById(Long id) throws Exception{
Company c = null;
try{
if(id == null){
throw new Exception("Failed to get company ID");
}
c = baseFacade.load(Company.class, id);
if(c == null || c.getId() == null){
throw new Exception("No company found");
}
}
catch(Exception e){
throw new Exception(e.getMessage());
}
finally{
return c;
} 开发者_运维知识库
}
As for the webservice class, there's a WebMethod invokes the above method:
@WebMethod(operationName = "findCompanyById", action = "urn:findCompanyById")
@WebResult(name = "Company")
public Company findCompanyById(@WebParam(name = "id") Long id) throws Exception{
return CompanyFacade.findCompanyById(id);
}
Below is the respond message I got, which is supposed to have the exception message:
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<ns2:findCompanyByIdResponse xmlns:ns2="http://site.com/api/ws"/>
</S:Body>
</S:Envelope>
The webservice works fine, the only problem is about the exception (e.g. No company found), the exception messages can be displayed in the Tomcat console, but not in the SOAP response message, it seems that the invoked method in the WebMethod doesn't return any exception. So the question is: how to parse the exception message from the method in backend to the SOAP response message OR is there any other design pattern? Thanks in advance!
SOAP doesn't deal with exceptions - it only knows about SOAP faults. In your case, the exception thrown by the findCompanyById method is wrapped in a SOAPFault and thrown back to the user.
You must create a class annotated with @WebFault
and that class must extend Exception
- this is the exception that your service should throw. Web Services don't know about runtime exceptions, so throwing unchecked exceptions from your service will not have any effect.
Alternatively, you can create a FaultBean, which can be specified in @WebFault
annotation, and will carry information about the specific error. The fields that you include in the FaultBean will be mapped to fields in the detail
tag of the SOAP response, whilst the message of your exception will be mapped to the faultstring
tag in your SOAP response.
An example follows:
@WebFault(faultBean = 'com.company.services.FaultBean')
public class NoCompanyFoundException extends Exception {
private FaultBean faultBean;
//getters, setters, etc
}
public class FaultBean {
// message and error code are totally arbitrary, other fields could be used
private String message;
private String errorCode;
}
精彩评论