2016-09-06 89 views
7

我正在使用android-priority-jobqueue,並使用retrofit對我的其餘api進行同步調用,但我不確定如何處理像401發送的未授權錯誤返回json陳述錯誤。簡單的做異步調用,但我正在適應我的應用程序作業經理。下面是IO異常的簡單嘗試,但401的422等?這個怎麼做?Retrofit 2同步調用錯誤處理4xx錯誤

try { 
    PostService postService = ServiceGenerator.createService(PostService.class); 
    final Call<Post> call = postService.addPost(post); 
    Post newPost = call.execute().body(); 

    // omitted code here 

} catch (IOException e) { 
    // handle error 
} 

編輯

使用改型響應對象是硬道理對我來說,返回改造響應對象讓我

Response<Post> response = call.execute(); 

if (response.isSuccessful()) { 
    // request successful (status code 200, 201) 
    Post result = response.body(); 

    // publish the post added event 
    EventBus.getDefault().post(new PostAddedEvent(result)); 
} else { 
    // request not successful (like 400,401,403 etc and 5xx) 
    renderApiError(response); 
} 

回答

5

檢查響應代碼,並顯示相應的消息。

試試這個:

PostService postService = ServiceGenerator.createService(PostService.class); 
final Call<Post> call = postService.addPost(post); 

Response<Post> newPostResponse = call.execute(); 

// Here call newPostResponse.code() to get response code 
int statusCode = newPostResponse.code(); 
if(statusCode == 200) 
    Post newPost = newPostResponse.body(); 
else if(statusCode == 401) 
    // Do some thing... 
+0

謝謝使用響應對象是我需要什麼,歡呼:) – CaptRisky

+0

很樂意幫助你。 –

+0

這樣做我得到一個'java.lang.NumberFormatException:無效的double:「」'錯誤,因爲call.execute返回一個空值的json。我想獲得call.execute()的主體並在做其他事情之前檢查它。當我寫「響應 newPostResponse = call.execute();」時,我得到一個錯誤,因爲身體不正確