How to handle AsyncTask failure

前端 未结 5 530
轻奢々
轻奢々 2021-01-04 06:09

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 o

5条回答
  •  清酒与你
    2021-01-04 06:40

    You can do this yourself pretty easily by creating a subclass of AsyncTask. Perhaps something like ErrorHandlingAsyncTask. First create an abstract callback method onException(Exception e). Your doInBackground(Generic... params) method should wrap all of its code in a try-catch block. In the catch block, call out to onException(Exception e) passing in your exception.

    Now, when you need this functionality, just override your new ErrorHandlingAsyncTask class.

    Quick and dirty pseudo code:

    class ErrorHandlingAsyncTask extends AsyncTask<..., ..., ...> {
        protected abstract void onException(Exception e);
    
        protected abstract ... realDoInBackground(...);
    
        protected ... doInBackground(...) {
            try {
                return realDoInBackground(...);
            } catch(Exception e) {
                onException(e);
            }
        }
    }
    

提交回复
热议问题