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 best pattern to implement the error handling in the SDK that better fits the Java language.
Let's say we have the rest endpoint: GET /photos/{photoId}
. This may return the following HTTP status codes:
The service looks something like this:
interface RestService { public Photo getPhoto(String photoID); }
In the code above I am not addressing the error handling yet. I obviously want to provide a way for the client of the sdk to know which error happened, to potentially recover from it. Error handling in Java is done using Exceptions, so let's go with that. However, what is the best way to do this using exceptions?
1. Have a single exception with information about the error.
public Photo getPhoto(String photoID) throws RestServiceException; public class RestServiceException extends Exception { int statusCode; ... }
The client of the sdk could then do something like this:
try { Photo photo = getPhoto("photo1"); } catch(RestServiceException e) { swtich(e.getStatusCode()) { case 401 : handleUnauthenticated(); break; case 403 : handleUnauthorized(); break; case 404 : handleNotFound(); break; } }
However I don't really like this solution mainly for 2 reasons:
2. Have a class hierarchy of errors
The method signature remains:
public Photo getPhoto(String photoID) throws RestServiceException;
But now we create exceptions for each error type:
public class UnauthenticatedException extends RestServiceException; public class UnauthorizedException extends RestServiceException; public class NotFoundException extends RestServiceException;
Now the client of the SDK could then do something like this:
try { Photo photo = getPhoto("photo1"); } catch(UnauthenticatedException e) { handleUnauthorized(); } catch(UnauthorizedException e) { handleUnauthenticated(); } catch(NotFoundException e) { handleNotFound(); }
With this approach the developer does not need to know about the HTTP status codes that generated the errors, he only has to handle Java Exceptions. Another advantage is that the developer may only catch the exceptions he wants to handle (unlike the previous situation where it would have to catch the single Exception (RestServiceException
) and only then decide if he wants to deal with it or not).
However, there's still one problem. By looking at the method's signature the developer still has no idea about the kind of errors he may need to handle because we only have the super class in the method's signature.
3. Have a class hierarchy of errors + list them in the method's signature
Ok, so what comes to mind now is to change the method's signature to:
public Photo getPhoto(String photoID) throws UnauthenticatedException, UnauthorizedException, NotFoundException;
However, it is possible that in the future new error situations could be added to this rest endpoint. That would mean adding a new Exception to the method's signature and that would be a breaking change to the java api. We would like to have a more robust solution that would not result in breaking changes to the api in the situation described.
4. Have a class hierarchy of errors (using Unchecked exceptions) + list them in the method's signature
So, what about Unchecked exceptions? If we change the RestServiceException to extend the RuntimeException:
public class RestServiceException extends RuntimeException
And we keep the method's signature:
public Photo getPhoto(String photoID) throws UnauthenticatedException, UnauthorizedException, NotFoundException;
This way I can add new exceptions to the method's signature without breaking existing code. However, with this solution the developer is not forced to catch any exception and won't notice that there are error situations he needs to handle until he carefully reads the documentation (yeah, right!) or noticed the Exceptions that are in the method's signature.
What's the best practice for error handling in these kind of situations?
Are there other (better) alternatives to the ones I mentioned?
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> T post(String url, Class<T> clazz, List<NameValuePair> 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 :]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With