Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Exception handling alternatives: Callbacks</strong></p> <p>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:</p> <pre><code> /** * 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(); </code></pre> <p>This is how the callback class looks like:</p> <pre><code>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. } } </code></pre> <p>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. </p> <p><strong>How can I define clearly what exceptions handle?</strong></p> <p>If you ask me, the best approach is draw the life-cycle of the request, something like this:</p> <p><img src="https://i.stack.imgur.com/XxXM7.png" alt="Sample exception lifecicle"></p> <p>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 <code>onAuthenticationError</code> is obligatory, not neccesarily the <code>onBadUsername</code> will be too, and viceversa. This is the point that makes this callbacks so flexible.</p> <p><strong>And how I implement the Http client?</strong></p> <p>Well I don't know much about http clients, I always use the <a href="http://hc.apache.org/httpclient-3.x/" rel="noreferrer">apache</a> 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</p> <pre><code>public class RestRequest { Gson gson = new Gson(); public &lt;T&gt; T post(String url, Class&lt;T&gt; clazz, List&lt;NameValuePair&gt; 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; } } </code></pre> <p>This is an example implementation of the <code>RestRequest</code>. 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).</p> <p>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.</p> <p>Hope this helps! Bye :]</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload