When .destfile is provided, gh will write to it even if the API returned an error:
library(gh)
# trying to download a file from a github repo that unexpectedly doesn't exist
> gh("/repos/r-lib/gh/contents/DOES_NOT_EXIST", .destfile="gh_destfile", .accept = "application/vnd.github.v3.raw")
Error in `gh_process_response()`:
! GitHub API error (404): Not Found
✖ URL not found:
<https://api.github.com/repos/r-lib/gh/contents/DOES_NOT_EXIST>
ℹ Read more at
<https://docs.github.com/rest/reference/repos#get-repository-content>
> readLines(file("gh_destfile"), warn=FALSE)
[1] "{\"message\":\"Not Found\",\"documentation_url\":\"https://docs.github.com/rest/reference/repos#get-repository-content\"}
In the absence of .destfile, when the request succeeds (e.g. change DOES_NOT_EXIST to README.md), the contents of the file are printed out. When it fails there's an error message, but nothing else is printed. However when .destfile is given, that file is written to whether or not the request succeeded. In the error case, the JSON-encoded error is put in the file even when .accept specified that we were expecting to write something other than JSON.
It's a bit of a surprising behaviour, and it's the underlying cause of a bug in usethis (r-lib/usethis#1774). Granted, usethis could have been handling the error more carefully.
I think it would be less surprising if the .destfile were only created and written when the API request succeeded. All data from the API error already appears in the R error, so we don't lose any information.
When
.destfileis provided,ghwill write to it even if the API returned an error:In the absence of
.destfile, when the request succeeds (e.g. changeDOES_NOT_EXISTtoREADME.md), the contents of the file are printed out. When it fails there's an error message, but nothing else is printed. However when.destfileis given, that file is written to whether or not the request succeeded. In the error case, the JSON-encoded error is put in the file even when.acceptspecified that we were expecting to write something other than JSON.It's a bit of a surprising behaviour, and it's the underlying cause of a bug in
usethis(r-lib/usethis#1774). Granted,usethiscould have been handling the error more carefully.I think it would be less surprising if the
.destfilewere only created and written when the API request succeeded. All data from the API error already appears in the R error, so we don't lose any information.