I have a small function in java that does a HTTP POST, and returns a JSON Object. This function return the JSON Object.
public JSONObject send_data(ArrayList<NameValuePair> params){
JSONObject response;
try {
response = new JSONObject(CustomHttpClient.executeHttpPost(URL, params).toString());
return response;
} catch(Exception e) {
// do smthng
}
}
This shows me an error that the function must return a JSONObject. how do i make it work? I cant send a JSONObject when there is an error, can I? It would be useless to send a blank jsonobject
This is because you are only returning a JSONObject if everything goes smoothly. However, if an exception gets thrown, you will enter the catch block and not return anything from the function.
You need to either
Return something in the catch block. For example:
//...
catch(Exception e) {
return null;
}
//...
Return something after the catch block. For example:
//...
catch (Exception e) {
//You should probably at least log a message here but we'll ignore that for brevity.
}
return null;
Throw an exception out of the method (if you choose this option, you will need to add throws to the declaration of send_data).
public JSONObject send_data(ArrayList<NameValuePair> params) throws Exception {
return new JSONObject(CustomHttpClient.executeHttpPost(URL, params).toString());
}
You could change it to this:
public JSONObject send_data(ArrayList<NameValuePair> params){
JSONObject response = null;
try {
response = new JSONObject(CustomHttpClient.executeHttpPost(URL, params).toString());
} catch(Exception e) {
// do smthng
}
return response;
}
There's a path through the function that doesn't return anything; the compiler doesn't like that.
You can change this to
catch(Exception e) {
// do smthng
return null; <-- added line
}
or put the return null (or some reasonable default value) after the exception block.
It's reasonble to return 'something' even in an error condition.
Look at JSend for a way to standardize your responses - http://labs.omniti.com/labs/jsend
In my opinion it's easiest to return an error json object and handle that on the client side then to solely rely on HTTP error codes since not all frameworks deal with those as well as they could.
The send_data() method should throw an exception so that the code calling send_data() has control over how it wants to handle the exception.
public JSONObject send_data(ArrayList<NameValuePair> params) throws Exception {
JSONObject response = new JSONObject(CustomHttpClient.executeHttpPost(URL, params).toString());
return response;
}
public void someOtherMethod(){
try{
JSONObject response = sendData(...);
//...
} catch (Exception e){
//do something like print an error message
System.out.println("Error sending request: " + e.getMessage());
}
}
I prefer one entry and one exit. Something like this seems reasonable to me:
public JSONObject send_data(ArrayList<NameValuePair> params)
{
JSONObject returnValue;
try
{
returnValue = new JSONObject(CustomHttpClient.executeHttpPost(URL, params).toString());
}
catch (Exception e)
{
returnValue = new JSONObject(); // empty json object .
// returnValue = null; // null if you like.
}
return returnValue;
}
Related
I am contemplating throwing a RuntimeException inside the catch block to solve the missing return statement.
What would be way to handle this situation?
I think throwing an exception of some kind instead of return some meaningless value. .
private String tryObjMapper(Object obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
//missing return statement
}
It depends on what you want to be the fallback/default value or error handling
You have 2 main options (with 2 sub options):
1.A.Throw the exception:
private String tryObjMapper(Object obj) throws JsonProcessingException {
return objectMapper.writeValueAsString(obj);
}
1.B.Rethrow RuntimeException (or custom unchecked exception)
private String tryObjMapper(Object obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new RuntimeException("Failed to map obj +" obj, e);
}
}
2.A.Define a default value on error
private String tryObjMapper(Object obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;//or other default value
}
2.B.Define a default value with a single return statement:
private String tryObjMapper(Object obj) {
String retVal = null;//or other default value
try {
retVal = objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return retVal ;
}
Consider logging exception using logger and not using e.printStackTrace()
I think that the best way to handle it is to return null at both catch block ant the end of the function. You must check the returnee from the function whether null or not before usage.
Note: This solution is suitable if only you can't change the signature of the function to declare that it throws an exception. Otherwise, go with the signature update.
I have a method which needs to return a JSONObject:
public JSONObject getDayJson(Date date) {
...
a few lines of code
...
return new JSONObject("..");
}
However this gives me an error as I need to catch any exceptions which may occur as a result of instantiating the JSONObject:
public JSONObject getDayJson(Date date) {
try {
...
a few lines of code
...
return new JSONObject("..");
} catch (Exception e) {
// need a return statement here!
}
}
This creates another error as in the catch block I am not returning the correct object type which is a JSONObject. If I do instantiate another JSONObject in the catch I need to nest another catch statement?!
You should better think what you want to do if an exception happens, but one option is to force a non exception calling constructor.
public JSONObject getDayJson(Date date) {
try {
...
a few lines of code
...
return new JSONObject("..");
} catch (Exception e) {
// doesn't throw another exception
return new JSONObject(new HashMap());
}
}
In the AsyncTask android. When calling a method in another class gets an exception which equals to null in the doInBackGround() task.
Even the hard coded inside the rest.request(url, method, json) doesn't work
protected JSONArray doInBackground(Void... arg0) {
try {
return rest.request(url, method, json); // <-- returns json array
} catch (Exception e) {
this.e = e;
}
return null; // <--- returning this null
}
Other things are like this,
private class doRequest extends AsyncTask<Void, JSONArray, JSONArray>
protected void onPostExecute(JSONArray data)
/*rest client class*/
public class AndrestClient {
// The client to use for requests
DefaultHttpClient client = new DefaultHttpClient();
public JSONArray request(String url, String method, String json) throws RESTException {
if (method.matches("GET")) {
return get(url);
} else if (method.matches("POST")) {
return post(url, json);
} else if (method.matches("PUT")) {
//return put(url, data);
} else if (method.matches("DELETE")) {
//return delete(url);
}
throw new RESTException("Error! Incorrect method provided: " + method);
}
public JSONArray get(String url) throws RESTException {
String jsonjr = "['Chanuthi','Damsith','Dunili','Isath','Minuka','Uvin','Vidath']";
JSONArray jsonAraay = null;
try {
jsonAraay = new JSONArray(jsonjr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonAraay;
}
}
The exception I got is e=null. All the other things work properly. When I am hard coding the result inside in the doInBackGround it works properly. Also the rest client get method returns the exact thing.
It appears you're using AsyncTask improperly. Firstly, you must subclass/nest your AsyncTask as per the Android documentation:
http://developer.android.com/reference/android/os/AsyncTask.html
In addition, you should follow the fundamental rules for calling methods of an outter class from a nested class.
There are some alternatives, like:
Create the AndrestClient object in onPreExecute() of the AsyncTask
Pass the AndrestClient object to the doInBackground as a parameter, then call its methods by doing something like this in the outter class:
doRequest.execute(rest);
i'm struggling with a JSONObject. I allready returned some json and converted it succesfully to objects and list of objects. My now i'm stuck.
This is the JSONObject i'm getting:
{"Result":true,"Messages":["Goe bezig!"]}
I'm able to get the Messages, but i can't seem to get the boolean in Result. Can somebody explain how to get it plz?
Here is the code:
public boolean Convert(JSONObject json) {
try
{
return json.getBoolean("Result");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
This worked fine for me, although it's pretty vague your question.
String jsonString = "{\"Result\":true,\"Messages\":[\"Goe bezig!\"]}";
JSONObject jsonObject = new JSONObject(jsonString);
boolean result = (Boolean) jsonObject.get("Result");
System.out.println(result);
You might want to catch at the end of your method Exception as well:
try {
return json.getBoolean("Result");
} catch (JSONException e) {
e.printStackTrace(); // replace these with `Log` statement
return false;
} catch (Exception e) {
e.printStackTrace(); // replace these with `Log` statement
return false;
}
How can I retrieve a file from the following method:
public void getJson(String pathToFile) {
String userUrl = DOMAIN_URL+pathToFile;
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(userUrl));
JSONArray outerJsonArray;
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
try {
JSONValue jsonValue = JSONParser.parse(response.getText());
JSONArray jsonArray = jsonValue.isArray();
if (jsonArray != null) {
} else {
throw new JSONException();
}
} catch (JSONException e) {
}
} else {
}
}
});
} catch (RequestException e) {
}
}
Now it is just void. I should retriwe the jsonArray variable
You simply can't.
The request is asynchronous, so your method has to be asynchronous (non-blocking) too. You can pass something like an AsyncCallback (to reuse an existing interface) to your getJson method, and have your RequestCallback call it... back, with the JSONArray.
Technically speaking, that would be possible, but that's a design choice in GWT to not allowing blocking AJAX requests.
Embrace asynchrony!
Just change the declaration to
public JSONArray getJson(String pathToFile) {
After the line
JSONArray jsonArray = jsonValue.isArray();
you can add
return jsonArray;
Now you have to be careful. Obviously, you have some error checking conditions in case the array is null or an error occurs during reading. It is up to you to design how to handle them: if the array is null, should you throw an exception or return the null value? If there is an error reading, should you throw an exception, print an error, or return a null value? These are considerations that your external interface will dictate.