0

Currently I'm working on implementing network communication layer. And I thought it's good to consult with more experienced Android developers first.

I have a class called WebApiController which is responsible for: making requests and parsing responses, and storing them in the models. WebApiController methods execute on the main thread, so I wrap them in AsyncTasks to take the load out of the main thread. WebApiController methods potentially throws exceptions such as ServerBadResponseException, XmlParserException, etc. And I want to be able to handle them accordingly to the type of error (i.e. show different error messages based on the type of error). So, what would be the best way to notify the onPostExecute about the error type, and nicely handle it there.

3 Answers3

1

Or this:

class SomeTask extends AsyncTask<Void, Void, Params> {

    @Override
    protected Params doInBackground(Void... voids) {
        Params params = new Params();
            try {
                .....
                params._result = .....
            } catch (Throwable e) {
                params._error = e;
            }
        return params;
    }

    @Override
    protected void onPostExecute(Params params) {
        if(params._error != null){
             .... 
        } else {
             .... 
        }
    }
}

class Params {
    public Throwable _error;
    public Object _result;
}
Vyacheslav Shylkin
  • 9,741
  • 5
  • 39
  • 34
1

Basically the easiest way is to set a return code like "SUCCESS", "FAILURE_XY" and process that in your onPostExecute(). This works also, when you normally would return data...

doInBackground() {
    try {
        // code
        return data;
    } catch (Exception e) {
        Log.e(TAG, "error description", e);
        resultCode = FAILURE;
        return null;
    }
}

onPostExecute(Data data) {
    if (data == null) {
        // check resultCode!
    } else {
        // work with your data
    }
}
WarrenFaith
  • 57,492
  • 25
  • 134
  • 150
  • What @appserv showed is basically the thing you are looking for. It is important to have at least an Enum or simple integers for a basic result code. According to the UX you should show error messages itself to the user. Just log them and show the user just that something went wrong. Don't even start to show them a real exception message! – WarrenFaith Feb 24 '12 at 10:37
0

You can try this (in doInBackgroung method):

        try {
            ........
        } catch (final Throwable e) {
            runOnUiThread(new Runnable() {
                public void run() {
                    Log.e(TAG, e.getMessage(), e);
                    Toast.makeText(......).show();
                }
            });
        }
Vyacheslav Shylkin
  • 9,741
  • 5
  • 39
  • 34