Kong / unirest-java

Unirest in Java: Simplified, lightweight HTTP client library.
http://kong.github.io/unirest-java/
MIT License
2.58k stars 591 forks source link

Provide access to the URL or HttpRequest from the HttpReponse #462

Closed gtaylor1981 closed 1 year ago

gtaylor1981 commented 1 year ago

I'm writing a generic error handling method to pass to ifFailure() and I want to log the URL where the error came from.

public static <T> Consumer<HttpResponse<T>> createErrorHandler(String source) {
    return httpResponse -> {
        LOG.warn(source + ": Error code " + httpResponse.getStatus() +" '" 
                        + httpResponse.getStatusText() + "' when querying URL " + "???");
    };
}

In my error handler where it says "???" above I would like to be able to do something like httpResponse.getUrl() or even httpResponse.getRequest().getUrl().

Simplified, I use the error handler like

var getResponse = Unirest.get().queryString("a", "x").asString().ifFailure(createErrorHandler("MyGetQuery"));
var postResponse = Unirest.post().body(jsonObject).asString().ifFailure(createErrorHandler("MyPostQuery"));

I can't see another way to do this, other than always passing the URL to the handler. As this is created dynamically I then have to break up the fluent API as I have to first create the request separately, then pass this to the error handler.

ryber commented 1 year ago

Hi @gtaylor1981 thanks for the suggestion. Yea the funny thing is, there is indeed a HttpRequestSummary object that is passed to the interceptors and metrics, and is literally just sitting right there where the Response is constructed, so it seems quite logical that it should be hung on the response object as well.

This class has the method, full request string (with query params), the raw string with param tokens, and a toString() method that returns it as a nice string suitable for logging that contains additional information about the body

This is done as of 3.14.1 / 4.0.0-RC7

Thanks again!