Skip to content

Commit

Permalink
feat: allow checking multiple errors codes in IsError
Browse files Browse the repository at this point in the history
  • Loading branch information
jooola committed Jul 23, 2024
1 parent 57f53c1 commit 2115e18
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
5 changes: 3 additions & 2 deletions hcloud/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"net"
"slices"
)

// ErrorCode represents an error code returned from the API.
Expand Down Expand Up @@ -127,10 +128,10 @@ type ErrorDetailsInvalidInputField struct {
}

// IsError returns whether err is an API error with the given error code.
func IsError(err error, code ErrorCode) bool {
func IsError(err error, code ...ErrorCode) bool {
var apiErr Error
ok := errors.As(err, &apiErr)
return ok && apiErr.Code == code
return ok && slices.Index(code, apiErr.Code) > -1
}

type InvalidIPError struct {
Expand Down
22 changes: 15 additions & 7 deletions hcloud/error_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ func TestError_Error(t *testing.T) {
func TestIsError(t *testing.T) {
type args struct {
err error
code ErrorCode
code []ErrorCode
}
tests := []struct {
name string
Expand All @@ -89,46 +89,54 @@ func TestIsError(t *testing.T) {
name: "hcloud error with code",
args: args{
err: Error{Code: ErrorCodeUnauthorized},
code: ErrorCodeUnauthorized,
code: []ErrorCode{ErrorCodeUnauthorized},
},
want: true,
},
{
name: "hcloud error with many codes",
args: args{
err: Error{Code: ErrorCodeUnauthorized},
code: []ErrorCode{ErrorCodeUnauthorized, ErrorCodeConflict},
},
want: true,
},
{
name: "hcloud error with different code",
args: args{
err: Error{Code: ErrorCodeConflict},
code: ErrorCodeUnauthorized,
code: []ErrorCode{ErrorCodeUnauthorized},
},
want: false,
},
{
name: "wrapped hcloud error with code",
args: args{
err: fmt.Errorf("wrapped: %w", Error{Code: ErrorCodeUnauthorized}),
code: ErrorCodeUnauthorized,
code: []ErrorCode{ErrorCodeUnauthorized},
},
want: true,
},
{
name: "wrapped hcloud error with different code",
args: args{
err: fmt.Errorf("wrapped: %w", Error{Code: ErrorCodeConflict}),
code: ErrorCodeUnauthorized,
code: []ErrorCode{ErrorCodeUnauthorized},
},
want: false,
},
{
name: "non-hcloud error",
args: args{
err: fmt.Errorf("something went wrong"),
code: ErrorCodeUnauthorized,
code: []ErrorCode{ErrorCodeUnauthorized},
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equalf(t, tt.want, IsError(tt.args.err, tt.args.code), "IsError(%v, %v)", tt.args.err, tt.args.code)
assert.Equalf(t, tt.want, IsError(tt.args.err, tt.args.code...), "IsError(%v, %v)", tt.args.err, tt.args.code)
})
}
}

0 comments on commit 2115e18

Please sign in to comment.