ErrorInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Response response = chain.proceed(request); if (response.code() >= 200 && response.code() <= 299) { return response; } ErrorFeed errorFeed = new Gson().fromJson(response.body().charStream(), ErrorFeed.class); if (errorFeed != null && errorFeed.errors != null && !errorFeed.errors.isEmpty()) { response.body().close(); throw errorFeed.errors.get(0); } return response; }  @Override Response intercept(Chain chain);  }
@Test public void throwsExceptionWhenError() throws Exception { Request request = new Request.Builder() .url(URL).build(); MediaType appJson = MediaType.parse("application/json"); Response response = new Response.Builder() .code(401) .protocol(Protocol.HTTP_1_1) .request(request) .body(ResponseBody.create(appJson, getSampleBodyStringForErrorCode(1000))) .build(); when(chain.proceed(any(Request.class))).thenReturn(response); try { interceptor.intercept(chain); fail("did not throw exception"); } catch(TapglueError e) { assertThat(e.getCode(), equalTo(1000)); } }