Best way to handle exceptions in a web services application

I have an application that consists of SOAP and REST web services and simple HTTP access. All of them convert incoming requests and send them to the handler. The most painful thing is handling exceptions. To return the correct answer, I have to wrap each method with a try-catch block and create an answer there.

I thought I could create a filter that could do this. But how can a filter recognize its source (soap, a leisure interface), so I knew that I should return SOAP or another answer?

+5
source share
4 answers

It depends on the WS environment you are using. All I know has some kind of interceptors / aspects that you can introduce and handle exceptions in one place. For example, inthere is even a special outgoing error chain where you can hook up your own interceptors.

Obviously, try-catchin every method is a bad idea.

+5
source

In the layer below Web-Service Layeryou need to create your own Exception, and in Web-Service Layeryou should use the approach try-catchto achieve occurred exceptionboth catchblock logand convert it to your custom web service level exception. I show this approach as follows:

@WebService
public class EmployeeWS
{
    @WebMethod
    public void add(Employee em) throws CustomWebServiceException
    {
       try
       {
         // call facade layer method  
       }
       catch(Exception e)
       {
          logger.error(e.getMessage());
          throw new CustomWebServiceException(e);
       }        
    }
}

, try catch Web-Method, AOP approch ( Spring AOP) interceptor Web-Service frameworks ( SOAPHandler<T> JAX-WS).

. JAX-WS throw a RuntimeException, Exception WSDL, throw a RuntimeException - CustomException, Web-Method .

Web-Service faramework.

+3

, - , . , Spring .

2 .

(1) Decorator: ,

try {
    call real method
} catch() {
   send error to client
}

, (, java 5). , ( ).

(2) API :

                    javax.servlet.ServletException                         //ErrorDisplay             

. http://java.sun.com/developer/technicalArticles/Servlets/servletapi2.3/

+1

All Articles