gpt4 book ai didi

android - Android中错误处理的正确方法

转载 作者:行者123 更新时间:2023-12-03 08:59:10 25 4
gpt4 key购买 nike

我有通过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;
}
}

最佳答案

我认为,如果您遇到错误(或成功举报,则应从RestClient处进行操作-正如您所说的那样,您将需要一种使用标准处理程序技术解决UI线程的方法。

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

关于android - Android中错误处理的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12912564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com