GoGridErrorHandler implements HttpErrorHandler { @Override public void handleError(HttpCommand command, HttpResponse response) { try { byte[] data = closeClientButKeepContentStream(response); String message = data != null ? new String(data) : null; Exception exception = message != null ? new HttpResponseException(command, response, message) : new HttpResponseException(command, response); Set<ErrorResponse> errors = parseErrorsFromContentOrNull(data); if (errors != null) exception = new GoGridResponseException(command, response, errors); switch (response.getStatusCode()) { case 400: if (Iterables.get(errors, 0).getMessage().indexOf("No object found") != -1) { exception = new ResourceNotFoundException(Iterables.get(errors, 0).getMessage(), exception); break; } break; case 403: exception = new AuthorizationException(exception.getMessage(), exception); break; } command.setException(exception); } finally { releasePayload(response); } } @Inject  GoGridErrorHandler(ParseJson<GenericResponseContainer<ErrorResponse>> errorParser); @Override void handleError(HttpCommand command, HttpResponse response);  }
@Test public void testHandler() { InputStream is = getClass().getResourceAsStream("/test_error_handler.json"); GoGridErrorHandler handler = Guice.createInjector(new GsonModule()).getInstance(GoGridErrorHandler.class); HttpCommand command = createHttpCommand(); handler.handleError(command, HttpResponse.builder().statusCode(200).message("ok").payload(is).build()); Exception createdException = command.getException(); assertNotNull(createdException, "There should've been an exception generated"); String message = createdException.getMessage(); assertTrue(message.contains("No object found that matches your input criteria."), "Didn't find the expected error cause in the exception message"); assertTrue(message.contains("IllegalArgumentException"), "Didn't find the expected error code in the exception message"); try { is.available(); throw new TestException("Stream wasn't closed by the GoGridErrorHandler when it should've"); } catch (IOException e) { } }