Best practice for handling HTTP error request

I sent this question to the Android development team, but I wanted to post it here for other people who might encounter design issues like me:

I was looking for an idiom or paradigm on how to handle HTTP errors.

Basically,

I have an AsyncTask that runs in a background thread that calls the static method my callRequest ().

This is all done in the doInBackground () part. There are two types of exceptions that executeRequest () throws. IOException for all communication errors and ServerErrorResponse exceptions, which is my own exception. This can happen if, for example, the client sent something bad to the server, all HTTP worked, but the server complained (maybe I passed an invalid parameter or id).

So, what I did is the result of the result in the "result object".

In onPostExecute (), I check if the result was unsuccessful, and then I try to process it in the user interface thread. However, now I have to start doing

Exception e = result.getException(); if (e != null) { if (e instanceof IOException) { //network error //handle network error here } else if (e instanceof ServerErrorResponseException) { //handle server error response here } 

As you can see, this is getting annoying. For each new exception, I have to check it with instanceof. Is there a way around this or a design that I could follow to avoid this? I want exceptions to be handled in the user interface thread in case I show a dialog box or something to the user.

Any ideas?

+4
source share
2 answers
 Exception e = result.getException(); if (e != null) { try { throw e; } catch (IOException ex) { //handle network error here } catch (ServerErrorResponseException ex) { //handle server error response here } catch (Exception ex) { //handle RuntimeException and others here //(You weren't just going to ignore them, were you?) } } 
+3
source

This is only one of several options:

Create an interface like

 public interface ResultReceiver { public void onSuccess(YourClass object); public void onError(Exception err); //alternatives to the former: public void onNetworkError(IOException err); //maybe the parameter is optional? public void onServerProblem(ServerErrorResponseException err); } 

Now, in your onPostExecute do something like

 result.handleWith(this); //I'm assuming your activity implements ``ResultReceiver`` interface 

If you prefer, you can create a result handler outside of your activity (this option is better to avoid code duplication between actions)

Finally, the handleWith implementation:

 public void handleWith(ResultReceiver handler){ Exception e = result.getException(); if (e != null) { if (e instanceof IOException) { //network error handler.onNetworkError(e); } else if (e instanceof ServerErrorResponseException) { handler.onServerProblem(e); } else { handler.onSuccess(this); } } 
+2
source

All Articles