How to handle errors in custom AsyncTaskLoader?
Asked Answered
N

2

14

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.

Nummulite answered 25/10, 2013 at 15:13 Comment(1)
Did you ever get anywhere with this? I am running into the same problem now that I don't have the return value from AsyncTask's doInBackground anymore to check.Otolaryngology
S
17

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()

Succuss answered 25/10, 2013 at 15:48 Comment(3)
Nice practice, did the sameYirinec
I've done this: MyLoader extends AsyncTaskLoader<Pair<MyDataClass, Exception>> You could also use a Bundle and have a key for errors, if all your data implements Parcelable.Ringler
Relevant read: tech.puredanger.com/2010/03/31/do-we-want-a-java-util-pairSuccuss
D
1

I've seen good results when returning a composite object that contains the payload (if any) and a status code, as you suggested. Then the Fragment that's hosting the AsyncTaskLoader can display an appropriate and informative error. This approach has the added advantage that it uses the built-in loader lifecycle.

Another option is to register a listener that your AsyncTaskLoader will notify when errors occur. The Facebook SDK has an example of using error listeners with loaders.

Dewees answered 25/10, 2013 at 15:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.