From 3efb632b316f495c98285f42c35aca9b5f089f6f Mon Sep 17 00:00:00 2001 From: Kegan Dougal Date: Mon, 24 Oct 2016 15:26:57 +0100 Subject: [PATCH] Log panicking HTTP requests Whilst Go does this by default (does not `exit`), it logs to the std logger which isn't written to the log file. Handle all panicking `OnIncomingRequests`. --- src/github.com/matrix-org/go-neb/server/server.go | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/github.com/matrix-org/go-neb/server/server.go b/src/github.com/matrix-org/go-neb/server/server.go index fa1bb7f..98d74d1 100644 --- a/src/github.com/matrix-org/go-neb/server/server.go +++ b/src/github.com/matrix-org/go-neb/server/server.go @@ -6,6 +6,7 @@ import ( log "github.com/Sirupsen/logrus" "github.com/matrix-org/go-neb/errors" "net/http" + "runtime/debug" ) // JSONRequestHandler represents an interface that must be satisfied in order to respond to incoming @@ -41,7 +42,17 @@ func MakeJSONAPI(handler JSONRequestHandler) http.HandlerFunc { "method": req.Method, "url": req.URL, }) - logger.Print(">>> Incoming request") + logger.Print("Incoming request") + defer func() { + if r := recover(); r != nil { + logger.WithField("error", r).Errorf( + "Request panicked!\n%s", debug.Stack(), + ) + jsonErrorResponse( + w, req, &errors.HTTPError{nil, "Internal Server Error", 500}, + ) + } + }() res, httpErr := handler.OnIncomingRequest(req) // Set common headers returned regardless of the outcome of the request