0

I have a method which needs to act based on response from an other service.

The expected response is {"status":"success"}

I have 2 methods in my java code.

String getResultParam( HttpUriRequest request ) {
    JSONObject res = getResult( request );
    return res.getString( "status");
}

JSONObject getResult( HttpUriRequest request ) {
    String res = // process the request and get the response String
    JSONObject jsonObj = new JSONObject(res);
}

The first is a generic method to execute any request and get the response string as a JSON. Here, new JSONObject(res) throws a JSONException.

The second method needs to get the status from the JSON after executing the request.Here, res.getString("status") again throws a JSONException.

How should I handle these exceptions?

  • Do I need to propogate the exeception as throws JSONException to all the methods using this method?
  • If I do need to propogate the exception to all the methods calling this method, where would be the point where I catch and handle the exception?
  • Do I need to catch the exception in the same method and throw a runtime exception?
  • Do I return null on the generic method?

What would be the proper design to handle this Exception? Any advice would be appreciated.

I'm using Tomcat Server, and not Spring.

pwecee
  • 1
  • 1

2 Answers2

0

Its always better to handle or throw a runtime exception in more specific methods you can see some java API from that you learned the designs with java is following the way java codes, handle the exception, etc.

  • Yes, my problem is on how to actually handle the above exceptions which **might** be thrown. – pwecee Jan 15 '20 at 07:09
0

1) propogate the exeception as throws JSONException to generic method

2) catch Exception and throw failure response or throw generic Exception

String getResultParam( HttpUriRequest request ) {
    try
    {
        JSONObject res = getResult( request );
        return res.getString( "status");
    } catch(Exception e){
    // Or Throw new  GenericException(e);
        return res.getString("failure");
    }
}
JSONObject getResult( HttpUriRequest request ) {
    String res = // process the request and get the response String
    JSONObject jsonObj = new JSONObject(res);
}
Mandar Dharurkar
  • 267
  • 1
  • 5
  • 16