2014-10-29 65 views
1

我正在使用Robospice提供的Retrofit模塊。我正在進行異步翻新調用。問題是,如果我的電話不成功,我會得到一個改進錯誤,但在robospice中,我得到onSuccess中的反饋,而不是onFailure(RobospiceException)。在RetrofitError中捕獲錯誤並將其傳遞給RoboSpice錯誤

我正在使用下面的代碼來執行我的web服務調用。

mSpiceManager.execute(mProfileRequest, new ProfileRequestListener()); 

在ProfileRequest的loaddatafromnetwork電話如下:

@Override 
public Profile loadDataFromNetwork() throws Exception { 
    initCountDownLatch(); 
    //Adding a retrofit callback. 
    getService().getProfile("//profileid", new AbstractCallback<Profile>() { 
     @Override 
     public void success(Profile profile, Response response) { 
      super.success(profile, response); 
      ProfileRequest.this.profile = profile; 
      mCountDownLatch.countDown(); 
     } 

     @Override 
     public void failure(RetrofitError retrofitError) { 
      super.failure(retrofitError); 
      mCountDownLatch.countDown(); 
     } 
    }); 
    mCountDownLatch.await(); 
    return profile; 
} 

任何人都可以讓我知道Robospice怎麼能看到獲得onFailure處?在簡單的話有沒有人嘗試過implmenting與改造「異步調用」 robospice(含改造回調實行「)?

回答

1

你應該扔在失敗RetrofitError()。

+0

扔它怎麼樣?如何在@Override上捕獲改進錯誤 public void onFailure(final SpiceException spiceException)? – SoH 2014-11-04 14:16:49

1

我要發表評論,@ Snicolas的答案,但

我相信@Snicolas所說的是,如果拋出異常,RoboSpice將捕獲它並將其打包到一個SpiceException中。您應該能夠使用RetrofitError來訪問RetrofitError getCause()方法:

mySpiceException.getCause()

,您可以嘗試投擲RetrofitError這樣的:

@Override 
public Profile loadDataFromNetwork() throws Exception { 
    initCountDownLatch(); 
    RetrofitError myRetrofitError = null; 
    //Adding a retrofit callback. 
    getService().getProfile("//profileid", new AbstractCallback<Profile>() { 
     @Override 
     public void success(Profile profile, Response response) { 
      super.success(profile, response); 
      ProfileRequest.this.profile = profile; 
      mCountDownLatch.countDown(); 
     } 

     @Override 
     public void failure(RetrofitError retrofitError) { 
      super.failure(retrofitError); 
      mCountDownLatch.countDown(); 
      myRetrofitError = retrofitError; 
     } 
    }); 
    mCountDownLatch.await(); 
    if (null != myRetrofitError) { 
     throw myRetrofitError; 
    } 
    return profile; 
} 

另外,爲什麼您使用的電話改裝的回調形式?有來電改造同步版本,以便你可以這樣做:

@Override 
public Profile loadDataFromNetwork() throws Exception { 
    Profile profile = getService().getProfile("//profileid"); 
    ProfileRequest.this.profile = profile; 
    return profile; 
} 

所有你需要做的是使用你的個人資料類GSON註解,使改造知道如何反序列化服務器的響應。改造將自動實例化和配置一個配置文件實例。然後你可以返回它。如果Retrofit在這個過程中遇到錯誤,它將拋出異常......然後因爲你沒有捕獲到RetrofitError,它就像我之前提到的那樣冒泡並被打包在SpiceException中。

+0

感謝MattC和Stephan。我以前使用同步改造方法。但我需要計算下載速度,我希望它能夠以中心的方式進行。 Retrofit響應對象給出了身體長度以及發送和接收時間。所以它很容易計算下載速度。但是我在同步改造呼叫中沒有得到Response方法嗎?因此我改變了我的回調。 – SoH 2014-11-07 10:35:32

+0

@SoH你實際上可以得到你想要的!用返回類型的Response聲明你的同步方法,你將得到原始的Retrofit Response對象。 – MattC 2014-11-07 20:42:59