Skip to content

Commit

Permalink
Correcting AsResponseError method
Browse files Browse the repository at this point in the history
  • Loading branch information
MovieStoreGuy committed Oct 24, 2024
1 parent 24238e7 commit 00bf849
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 7 deletions.
29 changes: 23 additions & 6 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,29 @@ func newResponseError(resp *http.Response, target int, targets ...int) error {
}
}

// IsResponseError is convenience function to see
// if it can convert into RequestError.
func IsResponseError(err error) (*ResponseError, bool) {
var re *ResponseError
if errors.As(err, &re) {
return err.(*ResponseError), true
// AsResponseError is a convenience function to check the error
// to see if it contains an `ResponseError` and returns the value with true.
// If the error was initially joined using [errors.Join], it will check each error
// within the list and return the first matching error.
func AsResponseError(err error) (*ResponseError, bool) {
// When `errors.Join` is called, it returns an error that
// matches the provided interface.
if joined, ok := err.(interface{ Unwrap() []error }); ok {
for _, err := range joined.Unwrap() {
if re, ok := AsResponseError(err); ok {
return re, ok
}
}
return nil, false
}

for err != nil {
if re, ok := err.(*ResponseError); ok {
return re, true
}
// In case the error is wrapped using `fmt.Errorf`
// this will also account for that.
err = errors.Unwrap(err)
}
return nil, false
}
Expand Down
13 changes: 12 additions & 1 deletion errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package signalfx

import (
"errors"
"fmt"
"io"
"net/http"
"net/url"
Expand Down Expand Up @@ -130,12 +131,22 @@ func TestIsRequestError(t *testing.T) {
err: &ResponseError{},
expected: true,
},
{
name: "joined errors",
err: errors.Join(errors.New("boom"), &ResponseError{}),
expected: true,
},
{
name: "fmt error",
err: fmt.Errorf("check permissions: %w", &ResponseError{}),
expected: true,
},
} {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()

_, ok := IsResponseError(tc.err)
_, ok := AsResponseError(tc.err)
assert.Equal(t, tc.expected, ok, "Must match the expected value")
})
}
Expand Down

0 comments on commit 00bf849

Please sign in to comment.