I have an instance of a Java class that I need to call some functions on, using the API exposed by another party. For each call, I need to both check for thrown exceptions, and check the value of the returned boolean. If the boolean is false, I need to read the errorMsg object to see what went wrong. In either error case, I need to throw an exception with a relevant method. Each method takes a different number of String arguments
I think there's a cleaner way to do this using reflection, but I can't figure out how to handle the different numbers of arguments. And there may be a totally different solution I've overlooked. Open to all suggestions. Any thoughts?
Here are two examples so you can see what I'm dealing with:
ClassProvidedWithExposedAPI s;
private void setHttp(JsonObject jo) throws Exception {
boolean success = true;
String errorString = null;
ArrayList<Message> errorMsg = new ArrayList<Message>();
try {
JsonObject http = jo.getAsJsonObject("http");
if (http != null && !http.isJsonNull()) {
success = s.setHttp(getJsonElementAsString(http, Http.ENABLED_ELEMENT),
getJsonElementAsString(http, Http.HTTP_PORT_ELEMENT),
getJsonElementAsString(http, Http.HTTPS_PORT_ELEMENT),
getJsonElementAsString(http, Http.TIMEOUT_ELEMENT),
getJsonElementAsString(http, Http.HTTP_REDIRECT_ELEMENT), errorMsg);
}
} catch (Exception e) {
errorString = e.toString();
} finally {
if (!success) {
if (errorString == null) {
errorString = errorMsg.toString();
}
throw new Exception("Exception in setHttp: " + errorString);
}
}
}
private void setSsh(JsonObject jo) throws Exception {
boolean success = true;
String errorString = null;
ArrayList<Message> errorMsg = new ArrayList<Message>();
try {
JsonObject ssh = jo.getAsJsonObject("ssh");
if (ssh != null && !ssh.isJsonNull()) {
success = s.setSsh(getJsonElementAsString(ssh, Ssh.ENABLED_ELEMENT),
getJsonElementAsString(ssh, Ssh.SSH_PORT_ELEMENT),
getJsonElementAsString(ssh, Ssh.TIMEOUT_ELEMENT), errorMsg);
}
} catch (Exception e) {
errorString = e.toString();
} finally {
if (!success) {
if (errorString == null) {
errorString = errorMsg.toString();
}
throw new Exception("Exception in setSsh: " + errorString);
}
}
}