首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >android错误处理的正确方法

问android错误处理的正确方法
EN

Stack Overflow用户
提问于 2012-10-16 18:23:43
回答 1查看 466关注 0票数 0

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

代码语言:javascript
复制
 Unreachable catch block for NoInternetException. This exception is never thrown from the try statement body

这意味着我应该从try活动语句中抛出异常。我尝试使用error的静态变量,并在RestClient中此变量为真的情况下抛出Activity中的异常。但我不认为这是最好的方法。另一个想法是处理RestClient类中的所有错误,但它不是一个活动,我应该使用处理程序或其他类似的方法来确定当前的活动,并显示我的网络失败的Toast消息。请告诉我最好的方法是什么。我的RestClient类:

代码语言:javascript
复制
  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;
     }
  }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-10-16 19:22:24

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12912564

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档