2016-09-06 87 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();”时,我得到一个错误,因为身体不正确