Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RestClient no longer returns an HTTPError #118

Closed
nedredmond opened this issue Apr 28, 2023 · 2 comments
Closed

RestClient no longer returns an HTTPError #118

nedredmond opened this issue Apr 28, 2023 · 2 comments

Comments

@nedredmond
Copy link

Before the bump to v2, I could do this:

import {
  ...
  "github.com/cli/go-gh/v2/pkg/api"
}
...

err = restClient.Get(path, &resp)
if err != nil {
  if err.(api.HTTPError).StatusCode == 404 {
    log.Fatal("special message")
  }
  log.Fatal("general message")
}

Since updating, that is no longer a valid casting. I tried doing errors.As, but that didn't seem to work either.

Based on some other repositories I found, I tried this:

import {
  ...
  ghApi "github.com/cli/go-gh/v2/pkg/api"
  "github.com/cli/cli/v2/api"
}
...

restClient, err := ghApi.DefaultRESTClient()
if err != nil {
  log.Fatal(err)
}
...

err = restClient.Get(path, &resp)
if err != nil {
  var httpErr api.HTTPError
  if errors.As(err, &httpErr) && httpErr.StatusCode == 404 {
    log.Fatal("special message")
  }
  log.Fatal("general message")
}

This is always going to the general Fatal response message and not the special message. It seems that the errors.As casting is not working here, and the error is a simple string error. I'd love to be able to parse this status code without examining the error string (which does return "HTTP 404: Not Found...").

Is there some new, undocumented method to consume these errors, or was this an accidental regression? Thanks.

@samcoe
Copy link
Contributor

samcoe commented Apr 30, 2023

@nedredmond This is not a regression but I did a poor job of explaining this change in the the release notes. I wrote

Change methods on HTTPError and GraphQLError custom error types to take pointers as method receivers.

but didn't explain when that would make an impact. This is the exact case, when trying to do type assertions on the errors returned from the clients. You should be able to change your code to assert that the type returned is *api.HTTPError rather than api.HTTPError.

  if err.(*api.HTTPError).StatusCode == 404 {
    log.Fatal("special message")
  }

Hope this helps. Going to close this for now but let me know if this does not fix your issue.

@samcoe samcoe closed this as completed Apr 30, 2023
@nedredmond
Copy link
Author

Thanks @samcoe-- I saw the note and thought it was a much more complicated migration somehow. Appreciate the help!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants