Skip to content

Commit 00991f2

Browse files
authored
Add new function "echo.StatusCode" to resolve status code from errors implementing HTTPStatusCoder interface
Add new function "echo.StatusCode" to resolve status code from errors implementing HTTPStatusCoder interface
2 parents 2c377f1 + 4dd9f46 commit 00991f2

2 files changed

Lines changed: 53 additions & 1 deletion

File tree

httperror.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,16 @@ type HTTPStatusCoder interface {
1414
StatusCode() int
1515
}
1616

17+
// StatusCode returns status code from error if it implements HTTPStatusCoder interface.
18+
// If error does not implement the interface it returns 0.
19+
func StatusCode(err error) int {
20+
var sc HTTPStatusCoder
21+
if errors.As(err, &sc) {
22+
return sc.StatusCode()
23+
}
24+
return 0
25+
}
26+
1727
// Following errors can produce HTTP status code by implementing HTTPStatusCoder interface
1828
var (
1929
ErrBadRequest = &httpError{http.StatusBadRequest} // 400

httperror_test.go

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@ package echo
55

66
import (
77
"errors"
8-
"github.com/stretchr/testify/assert"
8+
"fmt"
99
"net/http"
1010
"testing"
11+
12+
"github.com/stretchr/testify/assert"
1113
)
1214

1315
func TestHTTPError_StatusCode(t *testing.T) {
@@ -65,3 +67,43 @@ func TestNewHTTPError(t *testing.T) {
6567

6668
assert.Equal(t, err2, err)
6769
}
70+
71+
func TestStatusCode(t *testing.T) {
72+
var testCases = []struct {
73+
name string
74+
err error
75+
expect int
76+
}{
77+
{
78+
name: "ok, HTTPError",
79+
err: &HTTPError{Code: http.StatusNotFound},
80+
expect: http.StatusNotFound,
81+
},
82+
{
83+
name: "ok, sentinel error",
84+
err: ErrNotFound,
85+
expect: http.StatusNotFound,
86+
},
87+
{
88+
name: "ok, wrapped HTTPError",
89+
err: fmt.Errorf("wrapped: %w", &HTTPError{Code: http.StatusTeapot}),
90+
expect: http.StatusTeapot,
91+
},
92+
{
93+
name: "nok, normal error",
94+
err: errors.New("error"),
95+
expect: 0,
96+
},
97+
{
98+
name: "nok, nil",
99+
err: nil,
100+
expect: 0,
101+
},
102+
}
103+
104+
for _, tc := range testCases {
105+
t.Run(tc.name, func(t *testing.T) {
106+
assert.Equal(t, tc.expect, StatusCode(tc.err))
107+
})
108+
}
109+
}

0 commit comments

Comments
 (0)