How to handle AsyncTask failure

前端 未结 5 554
轻奢々
轻奢々 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:42

    What I always do is create a new Object (you can call it AsyncTaskResult or whatever you like) that can get returned with doInBackground. This Object would have two things:

    1. The expected result (String in your example)
    2. Error code or even if you want, the Exception object itself or a wrapped version of it. Anything that basically will help you handling error if any occurs

    I would then return this object to postExecute() and let that method check for the error, if there is then I handle it accordingly, otherwise I take the expected result and do whatever with it.

    The object would be something like:

    
    
    
         public class AsyncTaskResult {
                Exception exception;
                T asyncTaskResult;
    
                public void setResult(T asyncTaskResult) {
                    this.asyncTaskResult = asyncTaskResult;
                }
    
                public T getResult() {
                    return asyncTaskResult;
                }
    
                public void setException(Exception exception) {
                    this.exception = exception;
                }
    
                public boolean hasException() {
                    return exception != null;
                }
    
                public Exception getException() {
                    return exception;
                }
            }
    
    

    And your code becomes :

    
    
        /** this would be cool if it existed */
        protected void onError(Exception ex) {
            // handle error...
        }
    
        @Override
        protected AsyncTaskResult doInBackground(String... params) {
            AsyncTaskResult result = new AsyncTaskResult();
            try {
                // ... download ...
            } catch (IOException e) {
                result.setException(e);
            }
    
            return result;
        }       
    
        @Override
        protected void onPostExecute(AsyncTaskResult result) {
            if(result.hasException()) {
                // handle error here...
                onError(result.getException());
            } else {
                // deal with the result
            }
        }
    
    

提交回复
热议问题