android中错误处理的正确方法

时间:2012-10-16 10:23:43

标签: android exception exception-handling error-handling

我有通过RestClient连接到服务器的应用程序。我想在那里实现正确的错误处理方法,特别是如果用户丢失了互联网连接,则会发生ConnectException和HttpHostConnectException。 我在RestClient中使用所有PUT,GET,POST,DELETE方法实现了AsyncTask类,并在那里处理结果。我想抛出自己的异常,例如NoInternetConnection如果用户获得上面的异常匹配。并处理我自己的异常,重新加载当前的Activity并显示消息“No Internet”消息。 我试图在RestClient中处理HttpHostConnectException并抛出我的NoInternetConnection并在我的Activity中捕获它但是我得到了

 Unreachable catch block for NoInternetException. This exception is never thrown from the try statement body

这意味着我应该从Activity的try语句中抛出异常。我尝试使用错误的静态变量,如果此变量从RestClient为true,则从Activity中抛出异常。但我不认为这是最好的方法。 还有一个想法是处理RestClient类中的所有错误,但它不是一个Activity,我应该使用Handler或类似的东西来确定当前的Activity并显示我的Toast网络丢失消息。 请告诉我,最好的方法是什么。 我的RestClient类:

  public class RestClient
   {
     class AsyncExecute extends AsyncTask<RequestMethod, InputStream, Object> 
    {
          protected InputStream doInBackground(RequestMethod... param) {
              HttpUriRequest request;
                HttpResponse httpResponse;
                DefaultHttpClient client = getNewHttpClient();
                InputStream instream = null;
                RestClient.this.AddHeader(CoreProtocolPNames.USER_AGENT, "Android-AEApp,ID=2435743");
                RestClient.this.AddHeader(ClientPNames.COOKIE_POLICY,  CookiePolicy.RFC_2109);
                RestClient.this.AddHeader("User-Agent",  "Android-AEApp,ID=2435743");
                RestClient.this.AddHeader("Accept",  "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); 
                if (CookieStorage.getInstance().getArrayList().isEmpty())
                    CookieStorage.getInstance().getArrayList().add("PHPSESSID=lc89a2uu0rj6t2p219gc2cq4i2");
                RestClient.this.AddHeader("Cookie",  CookieStorage.getInstance().getArrayList().get(0).toString()); 
                switch(param[0]) {
                    case GET:
                    {
                        //add parameters
                        String combinedParams = "";
                        if(!params.isEmpty()){
                            combinedParams += "?";
                            for(NameValuePair p : params)
                            {
                                String paramString = null;
                                try {
                                    paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
                                } catch (UnsupportedEncodingException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                                if(combinedParams.length() > 1)
                                {
                                    combinedParams  +=  "&" + paramString;
                                }
                                else
                                {
                                    combinedParams += paramString;
                                }
                            }
                        }

                         request = new HttpGet(url + combinedParams);

                        //add headers
                        for(NameValuePair h : headers)
                        {
                            request.addHeader(h.getName(), h.getValue());
                        }

                       // executeRequest(request, url);
                        break;
                    }
                    case POST:
                    {
                        request = new HttpPost(url);

                        //add headers
                        for(NameValuePair h : headers)
                        {
                            request.addHeader(h.getName(), h.getValue());
                        }

                        if(!params.isEmpty()){
                            try {
                                ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                            } catch (UnsupportedEncodingException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }           
                        break;
                    }
                    case PUT:
                    {
                        request = new HttpPut(url);

                        //add headers
                        for(NameValuePair h : headers)
                        {
                            request.addHeader(h.getName(), h.getValue());
                        }

                        if(!params.isEmpty()){
                            try {
                                ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                            } catch (UnsupportedEncodingException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }


                        break;
                    }
                    case DELETE:
                    {
                        request = new HttpDelete(url);

                        //add headers
                        for(NameValuePair h : headers)
                        {
                            request.addHeader(h.getName(), h.getValue());
                        }

                        if(!params.isEmpty()){
                            try {
                                ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                            } catch (UnsupportedEncodingException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }

                        //executeRequest(request, url);
                        break;
                    }
                    default:
                        request = null;
                }

                try {
                    httpResponse = client.execute(request);
                    if (httpResponse.getLastHeader("Set-Cookie")!=null)
                    {
                        CookieStorage.getInstance().getArrayList().remove(0);
                        CookieStorage.getInstance().getArrayList().add(httpResponse.getLastHeader("Set-Cookie").getValue());
                    }
                    responseCode = httpResponse.getStatusLine().getStatusCode();
                    message = httpResponse.getStatusLine().getReasonPhrase();
                    Header[] headers = httpResponse.getAllHeaders();
                    for(Header head : headers)
                    {
                        Log.i("RestClient headers", head.toString());
                    }
                    Log.i("RestClient response status code", Integer.toString(responseCode));
                    if (responseCode == 401)
                    {

                        Intent i = new Intent(context,
                                LoginActivity.class);
                        i.putExtra("relogin", true);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(i);

                    }

                    HttpEntity entity = httpResponse.getEntity();
                    if (entity != null) {

                        instream = entity.getContent();

                    }

                } catch (ClientProtocolException e)  {

                    client.getConnectionManager().shutdown();
                    e.printStackTrace();
                } 

                catch (IOException e) {
                    client.getConnectionManager().shutdown();
                    publishProgress();
                    e.printStackTrace();
                }

                return instream;

          }
          protected void onProgressUpdate(Void... progress) {
              Toast.makeText(context, "You've lost internet connection. You should try later.",Toast.LENGTH_LONG)
               .show();
            }

            protected void onPostExecute(Object  result) {

                 if(result instanceof Exception) {
                        try {
                            throw new NoInternetException();
                        } catch (NoInternetException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    else{

                        super.onPostExecute((InputStream) result);
                        }
                    }

            }
    public InputStream Execute(RequestMethod method) throws Exception
    {   
        AsyncExecute mt = new AsyncExecute();
        mt.execute(method);
        InputStream stream  = (InputStream) mt.get();
        return stream;
     }
  }

1 个答案:

答案 0 :(得分:0)

我认为如果你有错误(或报告成功,你应该从RestClient中做到 - 正如你所说,你需要一种方法来使用标准处理程序技术来解决UI线程。

使用静态单例通常被认为是反模式,可能是一个坏主意。