我有通過RestClient連接到服務器的應用程序。我想在那裏實現正確的錯誤處理方法,特別是,如果用戶丟失了Internet連接,ConnectException和HttpHostConnectException。 我在RestClient中用所有的PUT,GET,POST,DELETE方法實現了AsyncTask類,並在那裏處理結果。我想拋出自己的異常,例如,如果用戶在上面獲得異常匹配,則返回NoInternetConnection。並處理我自己的例外情況,重新加載當前的活動並顯示「無互聯網」消息。 我試圖處理HttpHostConnectException在RESTClient實現,並把我的NoInternetConnection並抓住它在我的活動,但我得到了在android中的錯誤處理的正確方法
Unreachable catch block for NoInternetException. This exception is never thrown from the try statement body
這意味着我應該從活動的try語句把我的異常。我嘗試使用錯誤的靜態變量,並從Activity中拋出異常,如果此變量來自RestClient,則爲true。但我認爲這不是最好的方法。 還有一個想法是收集RestClient類中的所有錯誤,但它不是一個活動,我應該使用Handler或類似的方式來確定當前的活動並顯示我的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;
}
}