Retrofit 2 synchronous call error handling for 4xx Errors
<p>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?</p>

<pre><code>try {
    PostService postService = ServiceGenerator.createService(PostService.class);
    final Call&lt;Post&gt; call = postService.addPost(post);
    Post newPost = call.execute().body();

    // omitted code here

} catch (IOException e) {
    // handle error
}
</code></pre>

<p>EDIT</p>

<p>The use of the retrofit response object was the clincher for me, returning the retrofit response object allowed me to</p>

<pre><code>Response&lt;Post&gt; 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);
}
</code></pre>