Skip to content

Commit

Permalink
fix: invalid error unwrap for the httperror (#2753)
Browse files Browse the repository at this point in the history
Signed-off-by: saltbo <saltbo@foxmail.com>
  • Loading branch information
saltbo committed Mar 31, 2023
1 parent 715ef82 commit 77d4745
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 4 deletions.
10 changes: 6 additions & 4 deletions pkg/error/httperror.go
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package error

import (
"errors"
"fmt"
"io"
"net/http"
Expand Down Expand Up @@ -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 {
Expand All @@ -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
}

Expand Down
36 changes: 36 additions & 0 deletions 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)
}
}

0 comments on commit 77d4745

Please sign in to comment.