【发布时间】:2017-01-14 02:24:34
【问题描述】:
我正在使用 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
}
编辑
改造响应对象的使用对我来说是关键,返回改造响应对象让我能够
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);
}
【问题讨论】:
标签: android error-handling retrofit2 synchronous