Search code examples
javaoopobjectjava-meencapsulation

Encapsulating common exception handling logic


I have a series of web service method calls which all follow the below format. The only difference in each method is httpRequest.methodName(). Can anybody think of a way I can encapsulate the common logic? Also note that my environment is J2ME.

public Response webserviceCall(Request request) {

    HTTPRequest httpRequest = new HTTPRequest(new ConnectionProperties());

    String errorMessage = "";
    String errorCode = "";

    try {
        // the only thing different
        httpRequest.methodName();
    } catch (SDKException e) {
        errorMessage = e.getMessage();
        errorCode = e.getErrorCode();
    }

    Error error = new Error(errorMessage,errorCode);

    return new Response(error);
}

Solution

  • One alternative is to put that code in an abstract class, and change it to call an abstract method (name it process, for example):

    abstract class BaseWebService {
       public abstract Response process(HTTPRequest request) throws SDKException;
    
       public Response webserviceCall(Request request) {
    
           HTTPRequest httpRequest = new HTTPRequest(new ConnectionProperties());
    
           String errorMessage = "";
           String errorCode = "";
    
           try {
               process(httpRequest);
           } catch (SDKException e) {
               errorMessage = e.getMessage();
               errorCode = e.getErrorCode();
           }
    
           Error error = new Error(errorMessage,errorCode);
    
           return new Response(error);
       }
     }
    

    Then make each of your services extend that class and implement the process method as needed

    class OneService extends BaseWebService {
    
       Response process(HTTPRequest request) throws SDKException{
            return request.methodName();
       } 
    }
    

    For the records, this is the Template Method Pattern