Kong / unirest-java

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

Timeout handler method #309

Closed chromy96 closed 4 years ago

chromy96 commented 4 years ago

Is your feature request related to a problem? Please describe. From what I've seen by checking the code, when HTTP endpoint is unavailable (a timeout happens), Unirest will throw an unchecked UnirestException. If a programmer would like to deal with timeouts in some sensible way (e.g. backoff retries) the only option I see is to catch the unchecked exception and work from there.

Describe the solution you'd like Would it be possible to provide a handler method similar to .ifSuccess() and .ifFailure() that could be used to deal with timeouts in a more friendly manner?

ryber commented 4 years ago

I actually just introduced a common configurable error handler that is similar to the ifFailure one but is invoked during the request. Changing that from a lambda (or adding a override) to a more robust error handler that could intercept exceptions is certainly possible. Let me think about this.

One weird thing about that is that the request object might be in a weird state. Especially if had any partially consumed streams. I'll play around with it

ryber commented 4 years ago

One other thing you might be interested in is there is a issue about honoring Retry-After (https://github.com/Kong/unirest-java/issues/281)

I have a branch where this works perfectly with the synchronous client but not so much with the async client which seems to hate the idea of doing a http request inside of a lifecycle of a http request

ryber commented 4 years ago

@chromy96 take a look at this and tell me what you think: https://github.com/Kong/unirest-java/pull/313

ryber commented 4 years ago

any input @chromy96? Otherwise I will just close this. Keep in mind that I could also expose the number or re-attempts at a connection/socket failure. It's currently at 3. I'm not sure, after 3, that attempting another will be much use. But this could be valuable for error handling in a system prone to lots of failure.

chromy96 commented 4 years ago

@ryber Hi, sorry, I missed notification emails. Yes, this looks good for the use-case I had in mind which is reporting issues when reattempts fail.

Regarding attempts: I don't see that increasing the number of attempts is of much use, as you said. What might be useful is a backoff functionality, where a client waits more and more before it reattempts the connection, but that is too broad to discuss in this issue, I think.

ryber commented 4 years ago

This is released in 3.2.00, You can supply your own global interceptor which has a method for catching a connection failure.