From 77d47452427d8d1296c9bf4aaabc061ffcfa44a5 Mon Sep 17 00:00:00 2001 From: Ambor Date: Fri, 31 Mar 2023 14:53:37 +0800 Subject: [PATCH] fix: invalid error unwrap for the httperror (#2753) Signed-off-by: saltbo --- pkg/error/httperror.go | 10 ++++++---- pkg/error/httperror_test.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 4 deletions(-) create mode 100644 pkg/error/httperror_test.go diff --git a/pkg/error/httperror.go b/pkg/error/httperror.go index 49cde0be..6c06a894 100644 --- a/pkg/error/httperror.go +++ b/pkg/error/httperror.go @@ -17,6 +17,7 @@ limitations under the License. package error import ( + "errors" "fmt" "io" "net/http" @@ -106,8 +107,8 @@ func (err Error) Description() string { func GetHTTPError(err error) (int, string) { var msg string var code int - fe, ok := err.(Error) - if ok { + var fe Error + if errors.As(err, &fe) { code = fe.HTTPStatus() msg = fe.Message } else { @@ -118,10 +119,11 @@ func GetHTTPError(err error) (int, string) { } func IsNotFound(err error) bool { - fe, ok := err.(Error) - if !ok { + var fe Error + if !errors.As(err, &fe) { return false } + return fe.Code == ErrorNotFound } diff --git a/pkg/error/httperror_test.go b/pkg/error/httperror_test.go new file mode 100644 index 00000000..db457048 --- /dev/null +++ b/pkg/error/httperror_test.go @@ -0,0 +1,36 @@ +package error + +import ( + "net/http" + "testing" + + "github.com/pkg/errors" + "github.com/stretchr/testify/assert" +) + +func TestIsNotFound(t *testing.T) { + errs := map[error]bool{ + nil: false, + MakeError(ErrorNotFound, "someone not found"): true, + MakeError(ErrorTooManyRequests, "too many requests"): false, + errors.Wrap(MakeError(ErrorNotFound, "someone not found"), "other information"): true, + errors.Wrap(MakeError(ErrorTooManyRequests, "too many requests"), "other information"): false, + } + + for err, want := range errs { + assert.Equal(t, want, IsNotFound(err)) + } +} + +func TestGetHTTPError(t *testing.T) { + errs := map[int]error{ + http.StatusBadRequest: MakeError(ErrorInvalidArgument, ""), + http.StatusConflict: errors.Wrap(MakeError(ErrorNameExists, ""), ""), + http.StatusNotFound: errors.Wrap(MakeError(ErrorNotFound, ""), ""), + http.StatusTooManyRequests: errors.Wrap(MakeError(ErrorTooManyRequests, "too many requests"), "other information"), + } + for want, err := range errs { + code, _ := GetHTTPError(err) + assert.Equal(t, want, code) + } +}