We are building a Java SDK to simplify the access to one of our services that provide a REST API. This SDK is to be used by 3rd-party developers. I am struggling to find the bes
Exception handling alternatives: Callbacks
I don't know if it's a better alternative, but you could use callbacks. You can make some methods optional by providing a default implementation. Take a look to this:
/**
* Example 1.
* Some callbacks will be always executed even if they fail or
* not, all the request will finish.
* */
RestRequest request = RestRequest.get("http://myserver.com/photos/31",
Photo.class, new RestCallback(){
//I know that this error could be triggered, so I override the method.
@Override
public void onUnauthorized() {
//Handle this error, maybe pop up a login windows (?)
}
//I always must override this method.
@Override
public void onFinish () {
//Do some UI updates...
}
}).send();
This is how the callback class looks like:
public abstract class RestCallback {
public void onUnauthorized() {
//Override this method is optional.
}
public abstract void onFinish(); //Override this method is obligatory.
public void onError() {
//Override this method is optional.
}
public void onBadParamsError() {
//Override this method is optional.
}
}
Doing something like this you could define an request life-cycle, and manage every state of the request. You can make some methods optional to implement or not. You can get some general errors and give the chance at the user to implements the handling, like in the onError.
How can I define clearly what exceptions handle?
If you ask me, the best approach is draw the life-cycle of the request, something like this:
This is only a poor example, but the important it's keep in mind that all the methods implementation, could be or not, optionals. If onAuthenticationError
is obligatory, not neccesarily the onBadUsername
will be too, and viceversa. This is the point that makes this callbacks so flexible.
And how I implement the Http client?
Well I don't know much about http clients, I always use the apache HttpClient, but there's not a lot of differences between the http clients, the most have a little more or a little fewer features, but in the end, they are all just the same. Just pick up the http method, put the url, the params, and send. For this example I will use the apache HttpClient
public class RestRequest {
Gson gson = new Gson();
public T post(String url, Class clazz,
List parameters, RestCallback callback) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
// Add your data
httppost.setEntity(new UrlEncodedFormEntity(parameters));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
StringBuilder json = inputStreamToString(response.getEntity()
.getContent());
T gsonObject = gson.fromJson(json.toString(), clazz);
callback.onSuccess(); // Everything has gone OK
return gsonObject;
} catch (HttpResponseException e) {
// Here are the http error codes!
callback.onError();
switch (e.getStatusCode()) {
case 401:
callback.onAuthorizationError();
break;
case 403:
callback.onPermissionRefuse();
break;
case 404:
callback.onNonExistingPhoto();
break;
}
e.printStackTrace();
} catch (ConnectTimeoutException e) {
callback.onTimeOutError();
e.printStackTrace();
} catch (MalformedJsonException e) {
callback.onMalformedJson();
}
return null;
}
// Fast Implementation
private StringBuilder inputStreamToString(InputStream is)
throws IOException {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
// Return full string
return total;
}
}
This is an example implementation of the RestRequest
. This is only one simple example, theres a lot of topics to discuss when you are making your own rest client. For example, "what kind of json library use to parse?", "are you working for android or for java?" (this is important because I don't know if android supports some features of java 7 like multi-catch exceptions, and there's some technologies that isn't availabe for java or android and viceversa).
But the best that I can say you is code the sdk api in terms of the user, note that the lines to make the rest request are few.
Hope this helps! Bye :]