2

First, I would like to say I'm sorry for such an ambiguous title...

I would like to know how to handle exceptions in the following scenario... I have a Struts action that receives a string from a EJB:

try{       
  JSONObject data = new JSONObject(result);   //result is String 
  String gatewayId = data.getString("gatewayId");
  session.setAttribute("gatewayId", gatewayId);
}catch(Exception e){
  System.out.println(e.getMessage());
}

EDIT Imports are:

import org.apache.struts2.json.*;
import org.json.*;

In case A json is:

{"gatewayId":100, "mask":4}

In case B json is:

{"success":false, "errorDesc":"bla bla"}

If the gatewayId is in the JSON I have no problem, but the problem is that the JSON received from EJB can (but doesn't have to) have that key:value pair.

If there was a Boolean JsonObject.hasString() method I would have no exceptions thanks to checking the existance of the string first in if/else if statements, but this way I can't avoid exceptions...

The first thing I thought I could do was to have different catch blocks depending on the exception type, but it seems that all exceptions are of generic JSONException type and also I shouldn't put any JSON treating code in the catch block because that code could also be throwing it's exceptions.

Please, have in mind that I'm not looking for the exact solution of my JSON problem here, but rather a general explanation of how to solve this kind of problems when you don't have functions that help you avoid having exceptions...

I hope my question makes sense....

2
  • before putting into json object, could you display result and let me know what you have?? Commented Jun 11, 2012 at 10:37
  • Luigi, for completeness pls include the import statement that allows you to refer to JSONObject. Also it would be useful to have a simplified sample of the JSON string that you are processing. Commented Jun 11, 2012 at 10:58

1 Answer 1

3

try

data.has("gatewayId");

this would help.

Sign up to request clarification or add additional context in comments.

1 Comment

Pankraj, thanks... that would be the solution of this concrete problem, but imagine that the library had no data.has() method. I know that would be a bad library then :) Exception would be thrown if json key is not found... Basically the question is could you be using catch blocks as a flow control? somehow? :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.