Skip to content

Commit

Permalink
feat(apierror): add method to return HTTP status code conditionally (#…
Browse files Browse the repository at this point in the history
…274)

Fixes: #229
  • Loading branch information
codyoss committed May 22, 2023
1 parent 81e95c0 commit 5874431
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
10 changes: 10 additions & 0 deletions v2/apierror/apierror.go
Original file line number Diff line number Diff line change
Expand Up @@ -349,3 +349,13 @@ func parseHTTPDetails(gae *googleapi.Error) ErrDetails {

return parseDetails(details)
}

// HTTPCode returns the underlying HTTP response status code. This method returns
// `-1` if the underlying error is a [google.golang.org/grpc/status.Status]. To
// check gRPC error codes use [google.golang.org/grpc/status.Code].
func (a *APIError) HTTPCode() int {
if a.httpErr == nil {
return -1
}
return a.httpErr.Code
}
32 changes: 32 additions & 0 deletions v2/apierror/apierror_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -519,3 +519,35 @@ func toAPIError(e *errdetails.ErrorInfo) *APIError {
details: ErrDetails{ErrorInfo: e},
}
}

func TestHTTPCode(t *testing.T) {
tests := []struct {
name string
apierr *APIError
want int
}{
{
name: "basic http error",
apierr: &APIError{httpErr: &googleapi.Error{Code: 418}},
want: 418,
},
{
name: "http error, with unknown status",
apierr: &APIError{httpErr: &googleapi.Error{Code: 418}, status: status.New(codes.Unknown, "???")},
want: 418,
},
{
name: "gRPC error",
apierr: &APIError{status: status.New(codes.DataLoss, "where did it go?")},
want: -1,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.apierr.HTTPCode(); got != tt.want {
t.Errorf("HTTPCode() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit 5874431

Please sign in to comment.