Is there a specific way to handle failure in an AsyncTask? As far as I can tell the only way is with the return value of task. I'd like to be able to provide more details on the failure if possible, and null isn't very verbose.
Ideally it would provide an onError handler, but I don't think it has one.
class DownloadAsyncTask extends AsyncTask<String, Void, String> {
/** this would be cool if it existed */
@Override
protected void onError(Exception ex) {
...
}
@Override
protected String doInBackground(String... params) {
try {
... download ...
} catch (IOException e) {
setError(e); // maybe like this?
}
}
}
If you start an AsyncTask inside an Activity and you rotate the device, the Activity will be destroyed and a new instance will be created. But the AsyncTask will not die. It will go on living until it completes.
AsyncTask instances can only be used one time.
You can simply save the exception in a field and check it in onPostExecute()
(to ensure that any error handling code is run on the UI thread). Something like:
new AsyncTask<Void, Void, Boolean>() {
Exception error;
@Override
protected Boolean doInBackground(Void... params) {
try {
// do work
return true;
} catch (Exception e) {
error = e;
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
if (result) {
Toast.makeText(ctx, "Success!",
Toast.LENGTH_SHORT).show();
} else {
if (error != null) {
Toast.makeText(ctx, error.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
}
}
I modified Nicholas's code a bit, should you want to do something in the UI thread in exception.
Remember the AsyncTask can only be executed once after instantiated.
class ErrorHandlingAsyncTask extends AsyncTask<..., ..., ...> {
private Exception exception = null;
protected abstract void onResult(Result result);
protected abstract void onException(Exception e);
protected abstract ... realDoInBackground(...);
@Override
final protected void onPostExecute(Result result) {
if(result != null) {
onResult(result);
} else {
onException(exception);
}
}
@Override
protected ... doInBackground(...) {
try {
return realDoInBackground(...);
} catch(Exception e) {
exception = e;
}
return null;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With