Error Handling on Java SDK for REST API service

后端 未结 5 1337
小鲜肉
小鲜肉 2021-02-04 01:37

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

相关标签:
5条回答
  • 2021-02-04 02:08

    It all comes down to how informative your API error responses are. The more informative the error handling of the API is, the more informative the exception handling can be. I would believe the exceptions would only be as informative as the errors returned from the API.

    Example:

    { "status":404,"code":2001,"message":"Photo could not be found."}
    

    Following your first suggestion, if the Exception contained both the status and the API error code, the developer has a better understanding of what he needs to do and more option when it comes to exception handling. If the exception also contained the error message that was returned, as well, the developer shouldn't even need to reference the documentation.

    0 讨论(0)
  • 2021-02-04 02:10

    It seems you are doing things by "hand". I would recommend you0 give a try to Apache CXF.

    It's a neat implementation the JAX-RS API that enables you to almost forget about REST. It plays well with (also recommended) Spring.

    You simply write classes that implement your interfaces (API). What you need to do is to annotate the methods and parameters of your interfaces with JAX-RS annotations.

    Then, CXF does the magic.

    You throw normal Exceptions in your java code, and then use exception mapper on server/nd or client to translate between them and HTTP Status code.

    This way, on server/Java client side, you only deal with regular 100% Java exception, and CXF handles the HTTP for you: You have both the benefits of a clear REST API and a Java Client ready to be used by your users.

    The client can either be generated from your WDSL, or built at runtime from introspection of the interface annotations.

    See :

    1. http://cxf.apache.org/docs/jax-rs-basics.html#JAX-RSBasics-Exceptionhandling
    2. http://cxf.apache.org/docs/how-do-i-develop-a-client.html

    In our application, we have defined and mapped a set of error codes and their counterpart Exceptions :

    • 4XX Expected / Functional excecption (like bad arguments, empty sets, etc)
    • 5XX Unexpected / Unrecovable RunTimeException for internal errors that "should not happen"

    It follows both REST and Java standards.

    0 讨论(0)
  • 2021-02-04 02:16

    The solution may vary depending on your needs.

    • If it is supposed that there could appear unpredictable new exception types in the future, your second solution with checked exception hierarchy and method that throw their superclass RestServiceException is the best one. All known subclasses should be listed in the javadoc like Subclasses: {@link UnauthenticatedException}, ..., to let developers know what kind of of exceptions there could hide. It should be noticed that if some method could throw only few exceptions from this list, they should be described in the javadoc of this method using @throws.

    • This solution is also applicable in the case when all appearances of RestServiceException means that any of it's subclasses could hide behind it. But in this case, if RestServiceException subclasses hasn't their specific fields and methods, your first solution is preferrable, but with some modifications:

      public class RestServiceException extends Exception {
          private final Type type;
          public Type getType();
          ...
          public static enum Type {
              UNAUTHENTICATED,
              UNAUTHORISED,
              NOT_FOUND;
          }
      }
      
    • Also there is a good practice to create alternative method that will throw unchecked exception that wraps RestServiceException exeption itself for usage within ‘all-or-nothing’ business logic.

      public Photo getPhotoUnchecked(String photoID) {
          try {
              return getPhoto(photoID);
          catch (RestServiceException ex) {
              throw new RestServiceUncheckedException(ex);
          }
      }
      
    0 讨论(0)
  • 2021-02-04 02:23

    I've seen libraries that combine your suggestions 2 and 3, e.g.

    public Photo getPhoto(String photoID) throws RestServiceException, UnauthenticatedException, UnauthorizedException, NotFoundException;
    

    This way, when you add a new checked exception that extends RestServiceException, you're not changing the method's contract and any code using it still compiles.

    Compared to a callback or unchecked exception solution, an advantage is that this ensures your new error will be handled by the client code, even if it's only as a general error. In a callback, nothing would happen, and with an unchecked exception, your client application might crash.

    0 讨论(0)
  • 2021-02-04 02:24

    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:

    Sample exception lifecicle

    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 :]

    0 讨论(0)
提交回复
热议问题