Search code examples
jax-rsjava-ee-7jersey-client

How do I get the URL for the request when I get a BadRequestException in Jax-rs?


I'm getting a BadRequestException when using Jersey 2 and I'd like to get the URL that was used in the request and print it in the logs when the exception is caught.

Is there a property/method combination on the BadRequestException object that will return the URL? I don't see it in the JavaDocs, but it could have a name unrelated to "URL".


Solution

  • You can't get URI from BadRequestException. But you can get it from WebTarget you invoked the request on:

    WebTarget target = ClientBuilder.newClient().target("http://localhost");
    
    try {
        String result = target.request().get(String.class);
    } catch (BadRequestException bre) {
        // get the URI
        target.getUri();
    }
    

    If you don't want to use try-catch block:

    Response response = target.request().get();
    
    if (response.getStatus() == 200) {
        // OK
    } else {
        // Handle other state.
    }