Home > DeveloperSection > Forums > Encapsulating common exception handling logic
ezra heywood
ezra heywood

Total Post:145

Points:1019
Posted on    June-12-2013 5:20 AM

 OOPS OOPS 
Ratings:


 1 Reply(s)
 783  View(s)
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);

}



Vijay Shukla

Total Post:100

Points:700
Posted on    June-12-2013 7:56 AM

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

Don't want to miss updates? Please click the below button!

Follow MindStick