Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions httperror.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,16 @@ type HTTPStatusCoder interface {
StatusCode() int
}

// StatusCode returns status code from error if it implements HTTPStatusCoder interface.
// If error does not implement the interface it returns 0.
func StatusCode(err error) int {
var sc HTTPStatusCoder
if errors.As(err, &sc) {
return sc.StatusCode()
}
return 0
}

// Following errors can produce HTTP status code by implementing HTTPStatusCoder interface
var (
ErrBadRequest = &httpError{http.StatusBadRequest} // 400
Expand Down
44 changes: 43 additions & 1 deletion httperror_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ package echo

import (
"errors"
"github.com/stretchr/testify/assert"
"fmt"
"net/http"
"testing"

"github.com/stretchr/testify/assert"
)

func TestHTTPError_StatusCode(t *testing.T) {
Expand Down Expand Up @@ -65,3 +67,43 @@ func TestNewHTTPError(t *testing.T) {

assert.Equal(t, err2, err)
}

func TestStatusCode(t *testing.T) {
var testCases = []struct {
name string
err error
expect int
}{
{
name: "ok, HTTPError",
err: &HTTPError{Code: http.StatusNotFound},
expect: http.StatusNotFound,
},
{
name: "ok, sentinel error",
err: ErrNotFound,
expect: http.StatusNotFound,
},
{
name: "ok, wrapped HTTPError",
err: fmt.Errorf("wrapped: %w", &HTTPError{Code: http.StatusTeapot}),
expect: http.StatusTeapot,
},
{
name: "nok, normal error",
err: errors.New("error"),
expect: 0,
},
{
name: "nok, nil",
err: nil,
expect: 0,
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
assert.Equal(t, tc.expect, StatusCode(tc.err))
})
}
}
Loading