Reputation: 5407
I'm building an application in the Play Framework, and am facing a challenge in one of my function definitions. This isn't really a Play Framework question, but it applies to Play because sbt compile
fails because of this error.
So I have this function in one of my classes:
private JSONObject getJsonObject(String url) {
HttpResponse<JsonNode> response;
try {
response = Unirest.get(url).asJson();
} catch (UnirestException e) {
Logger.error("Failed to GET data. Connection string was: " + url);
e.printStackTrace();
}
return response.getBody().getObject();
}
The reason I decided to catch the Exception within the function was that I didn't want my function to throw
an exception. Because then, this try-catch
needs to be done at multiple places where the call is made to this function. I can avoid that by putting a throws UnirestExecption
but that would bubble up all the way across the entire function stack, all the way to class constructors.
However, with the current code, my IDE and sbt compile
both tell me:
[error]: variable response might not have been initialized
How do I get out of this in this case? I can't seem to do a new HttpResponse()
because the class definition looks too scary to me. I of course can't do another Unirest.get()
because that will throw an exception of its own!
What's a neater way out?
Upvotes: 0
Views: 1740
Reputation: 3426
What do you expect response to be if an exception is thrown?
If response = Unirest.get(url).asJson();
throws an exception, your response object will be uninitialized.
You can either wrap the exception caught and rethrow it like:
private JSONObject getJsonObject(String url) {
HttpResponse<JsonNode> response;
try {
response = Unirest.get(url).asJson();
} catch (UnirestException e) {
Logger.error("Failed to GET data. Connection string was: " + url);
throw new RuntimeException(e);
}
return response.getBody().getObject();
}
or return some default value if GET request fails:
private JSONObject getJsonObject(String url) {
HttpResponse<JsonNode> response;
try {
response = Unirest.get(url).asJson();
} catch (UnirestException e) {
Logger.error("Failed to GET data. Connection string was: " + url);
return null;
}
return response.getBody().getObject();
}
Upvotes: 1