Retrofit 2 synchronous call error handling for 4xx Errors

后端 未结 2 2076
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-13 15:00

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 sen

2条回答
  •  清酒与你
    2021-02-13 15:48

    Check response code and show the appropriate message.

    Try this:

     PostService postService = ServiceGenerator.createService(PostService.class);
     final Call call = postService.addPost(post);
    
    Response 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... 
    

提交回复
热议问题