ENCAPSULATING COMMON EXCEPTION HANDLING LOGIC

ezra heywood

Total Post:145

Points:1019
Posted by  ezra heywood
OOPS 
 1104  View(s)
Ratings:
Rate this:

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);

}

  1. Vijay Shukla

    Post:100

    Points:700
    Re: Encapsulating common exception handling logic

    Hello Ezra Heywood!

    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();
       } 
    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!