r-lib / gh

Minimalistic GitHub API client in R
https://gh.r-lib.org
Other
223 stars 52 forks source link

Return reponse header in error condition #117

Closed gadenbuie closed 2 years ago

gadenbuie commented 4 years ago

This small PR returns the response headers as $response in the error condition thrown from gh_error() to make it possible to use information returned in the headers by GitHub when handling the error.

In particular, this is useful when reaching rate limits as it would allow users to use the Retry-After or X-RateLimit-Reset properties to wait for the rate limit to reset or the retry-after period to pass.

# this search will quickly make too many requests per minute
# and trigger the abuse rate limit
err <- tryCatch(
  gh("/search/code", q = "foo", .limit = Inf),
  "http_error_403" = identity
)
err
#> <github_error in gh_process_response(raw): 
#> GitHub API error (403): 403 Forbidden
#> Message: You have triggered an abuse detection mechanism. Please wait a few minutes before you try again.
#> Read more at https://developer.github.com/v3/#abuse-rate-limits>

str(err$response[c("status", "retry-after")])
#> List of 2
#>  $ status     : chr "403 Forbidden"
#>  $ retry-after: chr "60"

I used response to align with the attribute name in a successful response.

x <- gh("/repos/r-lib/gh")
attributes(x)$response
#> ... response headers
gadenbuie commented 4 years ago

I renamed the headers item response_headers and added the response content as response_content.

I hope it's okay, but I rolled #116 into this PR as it also touches gh_error() and resolves an issue that occurs with conditional requests that don't return a response body. (In short, when the body is empty res is raw(0) so gh_error() fails when trying to access res$message.)

gaborcsardi commented 2 years ago

Thanks again and sorry for the long wait! I removed #116 because I think we handle that elsewhere now.