0

I'm calling a REST Service that returns a JSON String. It works, but I'm not sure how to handle the exceptions and return values. Here are my two methods I wrote:

public static String callRestService(String id) {

    try {
        URL url = new URL("http://"localhost:8080/rest/api/2/issue/" + id);
        String basicAuth = ConnectionHelper.getServerAuthentication(serverConfig.get("authenticationType"),
            serverConfig.get("username"), serverConfig.get("password"));
        HttpURLConnection connection = ConnectionHelper.getHttpURLConnection(url, "GET", "Accept", basicAuth);

        if (connection != null) {
            InputStream responseStream = connection.getInputStream();
            String response = StringHelper.convertInputStreamToString(responseStream);
            connection.disconnect();

            return response;
        }
        return "";

    } catch (Exception e) {
        return "";
    }
}

    public static HttpURLConnection getHttpURLConnection(URL url, String requestMethod, String requestProperty,
    String authentication) {

    try {
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();

        if (authentication != null && !authentication.isEmpty()) {
            connection.addRequestProperty("Authorization", authentication);
        }
        connection.setRequestMethod(requestMethod);
        connection.addRequestProperty(requestProperty, "application/json");

        return connection;
    } catch (Exception e) {
        return null;
    }
}

Is my return value and exception handling ok? Or is there a better way to do this?

4
  • You should call disconnect from within a finally block, so that it is called even in case of an error. Commented Aug 14, 2016 at 10:24
  • Ok, you are right. What about Exceptions and the return values in case of errors? Commented Aug 14, 2016 at 10:28
  • It's up to you how you want to handle exceptions and what you want to return in such cases. In general, it's better practice to log exceptions so that you would know they occurred. Commented Aug 14, 2016 at 10:30
  • I see. I planned to add logging later. Commented Aug 14, 2016 at 10:41

2 Answers 2

1

For better client side handling you should have an Enum with return cases for example if we are building a registration module your enum should be like the following :

 public enum RestResponseEnum{
    DONE(1,"done"),DUPLICATE_RECORD(2,"Sorry this is a duplicate record"),ERROR(3,"There is an error happened")
    //Getter & Setter
    private int code;
    //Getter & Setter
    private String msg;

private(int code,String msg){
          this.code=code;
          this.msg=msg;
}


public static String getAsJson(RestResponseEnum restResponseEnum){
      JSONObject jsonObject=new JSONObject();
      jsonObject.put("code", restResponseEnum.getCode());
      jsonObject.put("message", restResponseEnum.getMsg());
      return jsonObject.toString();
 }
}

Use it like this :

{
// Your function code
 if(registeredEmailIsFoundInDatabase){
  return RestResponseEnum.getAsJson(RestResponseEnum.DUPLICATE_RECORD);       
 }
}

You should always faclitate and clearify the response to the client you can see this methodology from dealing with most of apis like this one from github : https://api.github.com/users/any/any

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

Comments

1

If it is a proper REST service it will add additional information about a call in the http response code. So if it doesnt start with 2, there is no point in parsing the response body at all (in case there is no contract to return error details in the body).

How to handle your exception much depends on your current application. General rules of thumb are:

  1. Log exceptions
  2. Handle them on an appropriate level

Sometimes you need to ensure encapsulation and handle them where they occur, sometimes it's okay to rethrow them an catch them globally. E.g. you are using a framework like JSF, user has triggered an external service call, log the exception, rethrow it, catch it and inform the user about it without sharing too much technical details. Like:

Error: YOUR_ERROR_CODE has occured. Please contact technical support if this keeps happening.

Example:

if (connection.getResponseCode().startsWith("2") {
// do stuff
// if any checked exception occurs here, add it to throws clause and let the caller catch it
}
else if connection.getResponseCode().equals("404") {
  throw new EntityNotFoundRuntimeException(...);
}
...

But whether or not this solution is good for your case depends on your architecture.

Comments

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.