对4xx错误进行2次同步调用错误处理

Cap*_*sky 11 error-handling android synchronous retrofit2

我正在使用android-priority-jobqueue并且我使用改造来对我的rest api进行同步调用但是我不确定如何处理像401 Unauthorized错误这样的错误,我发回json说明错误.在进行异步调用时很简单,但我正在调整我的应用程序作为职位经理.下面是一个简单的尝试捕获IO异常,但401的422等?这该怎么做?

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
}
Run Code Online (Sandbox Code Playgroud)

编辑

使用改装响应对象是我的关键,返回改装响应对象允许我

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);
}
Run Code Online (Sandbox Code Playgroud)

FAЯ*_*ЯAƸ 7

检查响应代码并显示相应的消息.

试试这个:

 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... 
Run Code Online (Sandbox Code Playgroud)