简体   繁体   中英

Java: Exception and Return Value handling in REST service consume

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?

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. Eg 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM