Skip to content

Instantly share code, notes, and snippets.

@mmichler
Last active September 4, 2017 06:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmichler/a2637358fc5cd44922c4abad863f5461 to your computer and use it in GitHub Desktop.
Save mmichler/a2637358fc5cd44922c4abad863f5461 to your computer and use it in GitHub Desktop.
'AsyncTask'-derived class that handles RuntimeExceptions and throws them on the UI thread
package app.meetling.io;
import android.os.AsyncTask;
/**
* <code>AsyncTask</code> that handles RuntimeExceptions and throws them on the UI thread. Use
* <code>doInBgCatchError</code> for computation code. If you overwrite <code>onPostExecute<code>,
* call <code>super<code> to handle errors. For <code>try-with-resources</code>, overwrite
* <code>doInBackground()<code> and set error manually.
*/
abstract class ErrorHandlingTask<Params, Progress, Result>
extends AsyncTask<Params, Progress, Result> {
private RuntimeException mError;
public void setError(RuntimeException e) {
mError = e;
}
@Override
protected Result doInBackground(Params... params) {
try {
return doInBgCatchError(params);
} catch (RuntimeException e) {
setError(e);
return null;
}
}
protected Result doInBgCatchError(Params... params) {
return null;
}
@Override
protected void onPostExecute(Result result) {
if (mError != null) {
throw mError;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment