Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DefaultHTTPErrorHandler: return error if marshalling JSON fails #2022

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 16 additions & 0 deletions echo.go
Expand Up @@ -401,6 +401,22 @@ func (e *Echo) DefaultHTTPErrorHandler(err error, c Context) {
}
if err != nil {
e.Logger.Error(err)

if e.Debug {
message = Map{"message": http.StatusText(http.StatusInternalServerError), "error": err.Error()}
} else {
message = Map{"message": http.StatusText(http.StatusInternalServerError)}
}

if c.Request().Method == http.MethodHead {
err = c.NoContent(http.StatusInternalServerError)
} else {
err = c.JSON(http.StatusInternalServerError, message)
}
if err != nil {
e.Logger.Error("Sending internal message failed as well:", err)
// TODO maybe cancel whole connection here?
}
}
}

Expand Down
14 changes: 14 additions & 0 deletions echo_test.go
Expand Up @@ -1132,6 +1132,14 @@ func TestDefaultHTTPErrorHandler(t *testing.T) {
err := errors.New("internal error message body")
return NewHTTPError(http.StatusBadRequest).SetInternal(err)
})
e.GET("/bad-json", func(c Context) error {
err := errors.New("test error")
return c.JSON(http.StatusOK, err.Error) // <- missing () after 'Error'
})
e.GET("/bad-json-err", func(c Context) error {
err := errors.New("test error")
return NewHTTPError(http.StatusBadRequest, err.Error) // <- missing () after 'Error'
})

// With Debug=true plain response contains error message
c, b := request(http.MethodGet, "/plain", e)
Expand All @@ -1153,6 +1161,12 @@ func TestDefaultHTTPErrorHandler(t *testing.T) {
c, b = request(http.MethodGet, "/internal-error", e)
assert.Equal(t, http.StatusBadRequest, c)
assert.Equal(t, "{\n \"error\": \"code=400, message=Bad Request, internal=internal error message body\",\n \"message\": \"Bad Request\"\n}\n", b)
c, b = request(http.MethodGet, "/bad-json", e)
assert.Equal(t, http.StatusInternalServerError, c)
assert.Equal(t, "{\n \"error\": \"json: unsupported type: func() string\",\n \"message\": \"Internal Server Error\"\n}\n", b)
c, b = request(http.MethodGet, "/bad-json-err", e)
assert.Equal(t, http.StatusInternalServerError, c)
assert.Equal(t, "{\n \"error\": \"json: unsupported type: func() string\",\n \"message\": \"Internal Server Error\"\n}\n", b)

e.Debug = false
// With Debug=false the error response is shortened
Expand Down