I am currently developing an EJB3 based SOAP webservice and I wonder what are the best practices to handles uncatched exceptions and return a well formated SOAP response to the client.
example:
@WebMethod
public SomeResponse processSomeService(
@WebParam(name = "someParameters") SomeParameters someParameters)
{
// the EJB do something with the parameters
// and retrieve a response fot the client
SomeResponse theResponse = this.doSomething(someParameters);
return theResponse;
}
Do I have to catch generic exception like:
@WebMethod
public SomeResponse processSomeService(
@WebParam(name = "someParameters") SomeParameters someParameters)
{
// the EJB do something with the parameters
/开发者_Python百科/ and retrieve a response to return to the client
try
{
SomeResponse theResponse = this.doSomething(someParameters);
}
catch (Exception ex)
{
// log the exception
logger.log(Level.SEVERE, "something is going wrong {0}", ex.getMessage());
// get a generic error response not to let the
// technical reason going to the client
SomeResponse theResponse = SomeResponse.createError();
}
return theResponse;
}
Is there some kind of "best practice" in order to achieve this ?
Thank you
It is not good practice to return the error in the response, SOAP defines a SOAP fault for handling the return of errors. As was pointed out by Michael Konietzka, the container can handle the exception thrown and convert it to a SOAP fault.
In your case though, it seems you would like to catch and log the exception first - throw a new EJBException wrapping the original exception.
If you want to return a SOAP message in the event of an error, you'll have to create it. I wouldn't expect a container to know what you need.
I would say that your design is adequate. The one criticism I'd have is that you can't be specific about the nature of the error.
No need to catch them, the ejb-container will handle this.
UPDATE regarding the comment #1 by Alexandre GUIDET
From the EJB 3.1 specification, Chapter 14.2.2 Exception Handling -> System Exception:
If the bean method encounters a system exception or error, it should simply propagate the error from the bean method to the container (i.e., the bean method does not have to catch the exception).
If the bean method performs an operation that results in a checked exception that the bean method cannot recover, the bean method should throw the javax.ejb.EJBException that wraps the original exception.
Any other unexpected error conditions should be reported using the javax.ejb.EJBException.
So propagating the RuntimeException to the container is the way the EJB specification recommends.
精彩评论