我正在使用 android-priority-jobqueue 并使用改造来同步调用我的其余 api,但我不确定如何处理诸如 401 Unauthorized 错误之类的错误,我会发回 json 来说明错误。进行异步调用时很简单,但我正在调整我的应用程序以适应作业管理器。下面是一个简单的 IO 异常的 try catch,但是 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
}
EDIT
使用改造响应对象对我来说是关键,返回改造响应对象使我能够
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);
}
检查响应代码并显示相应的消息。
尝试这个:
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...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)