Skip to content

Commit e25457b

Browse files
author
Mohammad Alian
committed
return first if response is already committed in DefaultHTTPErrorHandler
1 parent 499097e commit e25457b

File tree

2 files changed

+41
-9
lines changed

2 files changed

+41
-9
lines changed

echo.go

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,11 @@ func (e *Echo) Routers() map[string]*Router {
358358
// DefaultHTTPErrorHandler is the default HTTP error handler. It sends a JSON response
359359
// with status code.
360360
func (e *Echo) DefaultHTTPErrorHandler(err error, c Context) {
361+
362+
if c.Response().Committed {
363+
return
364+
}
365+
361366
he, ok := err.(*HTTPError)
362367
if ok {
363368
if he.Internal != nil {
@@ -384,15 +389,13 @@ func (e *Echo) DefaultHTTPErrorHandler(err error, c Context) {
384389
}
385390

386391
// Send response
387-
if !c.Response().Committed {
388-
if c.Request().Method == http.MethodHead { // Issue #608
389-
err = c.NoContent(he.Code)
390-
} else {
391-
err = c.JSON(code, message)
392-
}
393-
if err != nil {
394-
e.Logger.Error(err)
395-
}
392+
if c.Request().Method == http.MethodHead { // Issue #608
393+
err = c.NoContent(he.Code)
394+
} else {
395+
err = c.JSON(code, message)
396+
}
397+
if err != nil {
398+
e.Logger.Error(err)
396399
}
397400
}
398401

echo_test.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import (
1717
"testing"
1818
"time"
1919

20+
`github.com/labstack/gommon/log`
2021
"github.com/stretchr/testify/assert"
2122
"github.com/stretchr/testify/require"
2223
"golang.org/x/net/http2"
@@ -252,6 +253,34 @@ func TestEchoFile(t *testing.T) {
252253
assert.NotEmpty(t, b)
253254
}
254255

256+
func TestEchoErrorHandlerEarlyReturn(t *testing.T) {
257+
e := New()
258+
259+
// Routes
260+
e.GET("/", func(c Context) error {
261+
c.String(http.StatusOK, "OK")
262+
return errors.New("ERROR")
263+
})
264+
265+
c, b := request(http.MethodGet, "/", e)
266+
assert.Equal(t, http.StatusOK, c)
267+
assert.Equal(t, "OK", b)
268+
}
269+
270+
func TestEchoErrorHandlerInternalError(t *testing.T) {
271+
e := New()
272+
err := errors.New("internal error")
273+
e.Logger.SetLevel(log.DEBUG)
274+
// Routes
275+
e.GET("/", func(c Context) error {
276+
return NewHTTPError(http.StatusBadRequest).SetInternal(err)
277+
})
278+
279+
c, b := request(http.MethodGet, "/", e)
280+
assert.Equal(t, http.StatusBadRequest, c)
281+
assert.Equal(t, `{"message":"Bad Request"}`+"\n", b)
282+
}
283+
255284
func TestEchoMiddleware(t *testing.T) {
256285
e := New()
257286
buf := new(bytes.Buffer)

0 commit comments

Comments
 (0)