Skip to content

Commit

Permalink
fix(http): return error in case of panic (#250)
Browse files Browse the repository at this point in the history
  • Loading branch information
fabiobozzo authored Apr 15, 2024
1 parent 84704fd commit dca860d
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
12 changes: 12 additions & 0 deletions http/errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,18 @@ func TestErrors(t *testing.T) {
status: "200 OK",
bodyStr: "the reader call returns a reader.",
},

{
path: []string{"panic"},
status: "500 Internal Server Error",
bodyStr: `{"Message":"an error occurred","Code":0,"Type":"error"}` + "\n",
},
{
path: []string{"latepanic"},
status: "200 OK",
bodyStr: `"some value"` + "\n",
errTrailer: "an error occurred",
},
}

mkTest := func(tc testcase) func(*testing.T) {
Expand Down
12 changes: 11 additions & 1 deletion http/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,21 @@ type requestLogger interface {
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log.Debug("incoming API request: ", r.URL)

var re ResponseEmitter

defer func() {
if r := recover(); r != nil {
log.Error("a panic has occurred in the commands handler!")
log.Error(r)
log.Errorf("stack trace:\n%s", debug.Stack())

if re != nil {
if err := re.CloseWithError(errors.New("an error occurred")); err != nil {
log.Errorf("error closing ResponseEmitter: %s", err)

return
}
}
}
}()

Expand Down Expand Up @@ -178,7 +188,7 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
defer cancel()

re, err := NewResponseEmitter(w, r.Method, req, withRequestBodyEOFChan(bodyEOFChan))
re, err = NewResponseEmitter(w, r.Method, req, withRequestBodyEOFChan(bodyEOFChan))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
Expand Down
13 changes: 13 additions & 0 deletions http/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,19 @@ var (
}),
},
},

"panic": {
Run: func(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment) error {
panic("Invalid memory address or nil pointer dereference")
},
},
"latepanic": {
Run: func(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment) error {
re.Emit("some value")
panic("Invalid memory address or nil pointer dereference")
},
Type: "",
},
},
}
)
Expand Down

0 comments on commit dca860d

Please sign in to comment.