改进2个同步呼叫错误处理以解决4xx错误 [英] Retrofit 2 synchronous call error handling for 4xx Errors
问题描述
我正在使用android-priority-jobqueue,并且我使用改造来对我的rest api进行同步调用,但是我不确定如何处理诸如401未经授权的错误之类的错误,我会向json发送回去说明错误。进行异步呼叫时很简单,但我正在为工作经理调整我的应用程序。以下是IO异常的简单尝试,但是401的422等等?
I'm using a android-priority-jobqueue and I use retrofit to make synchronous calls to my rest api but i'm unsure how to handle errors like 401 Unauthorized errors which I send back json stating the error. Simple when doing async calls but I'm adapting my app for job manager. below is a simple try catch for IO exceptions, but 401's 422's etc? How to do this?
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
}
编辑
对我来说,改型响应对象的使用至关重要改造响应对象允许我
The use of the retrofit response object was the clincher for me, returning the retrofit response object allowed me to
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);
}
推荐答案
检查响应代码并显示适当的消息。
Check response code and show the appropriate message.
尝试一下:
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...
这篇关于改进2个同步呼叫错误处理以解决4xx错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!