Last active
September 4, 2017 06:39
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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