Search code examples
restclientjerseyhttp-status-codes

Simulating Error Codes in Jersey REST Client


I am writing a REST service and also a REST client to call said service.

We have a bunch of error codes, some are retry-able, some are not. I want to write a client that retries if possible and otherwise surfaces these errors. My main issue right now is that I don't know how to simulate the responses I want to handle.

For example I'm doing:

Client client = Client.create();
    WebResource resource = client.resource("http://localhost:<port>/test");
    resource.type(MediaType.APPLICATION_JSON);
    ClientResponse response = resource.get(ClientResponse.class);

    if (response.getClientResponseStatus().getStatusCode() == 404) {
           //do something
    }

Is there a good way to overwrite a particular class or set a handler on this so that I can simulate all of the error codes I want to test and handle?


Solution

  • Here is the answer I've come up with:

    I did not know how to set status on a response, earlier, but it can be achieved with an HTTPServletResponse local field.

    Then based on some property in your REST call you can return a specific response by dong response.setStatus(440) or whatever.

    Don't forget to put a @Context annotation on your response so that jersey magic can instantiate it.

    @Context HTTPServletResponse response;