Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle errors in custom AsyncTaskLoader?

I am extending AsyncTaskLoader which I use later in a Fragment through LoaderManager. Is there suggested way to handle errors which occur during async task? I would like to popup message asking user to cancel or retry when internet connection error occurs.

Only way which I can think of now is to make Loader to return null on error or wrap loaded object into another which would have status code.

like image 786
Malachiasz Avatar asked Oct 25 '13 15:10

Malachiasz


1 Answers

What we did in our last project: Create a Wrapper that holds a generic and an excpetion like this:

public class AsyncTaskResult<T> {
   private final T result;
   private final Exception error;
   //getter & setter
}

Catch all Exceptions in your doInBackground(...) and pack them into the result wrapper (or the result if no error). In your UI check the wrapper if it's an exception, then show according error message, otherwise populate the fields with the result.

For us it was also good practice to define what unique types of exceptions, there are (e.g. exception with a recoverable error where you only show a dialog or an app failure where you need to kick the user to the main menu) and only throw these kinds (on catching the specific in your asynctask), so you don't have to bother with hundreds of different exceptions and also abstract your error handling. You could also provide String keys with the correct I18n error message so you only have to write e.getMessage()

like image 50
Patrick Favre Avatar answered Sep 28 '22 11:09

Patrick Favre