From e5fcf13373accd1eb536d59b0de857c353b30a8b Mon Sep 17 00:00:00 2001 From: Ali Raza <87068339+aliraza556@users.noreply.github.com> Date: Tue, 17 Dec 2024 19:30:51 +0500 Subject: [PATCH] Add stack trace logging for internal server errors (500) (#2204) * feat: add stack trace logging for 500 internal server errors * remove unnecessarily comment * feat: Implement stack trace capture for 500 errors --- routes/index.go | 27 +++++++++++++++++++++------ routes/test_routes.go | 17 +++++++++++++++++ 2 files changed, 38 insertions(+), 6 deletions(-) create mode 100644 routes/test_routes.go diff --git a/routes/index.go b/routes/index.go index bc12cdc1b..58806897d 100644 --- a/routes/index.go +++ b/routes/index.go @@ -6,6 +6,7 @@ import ( "io" "net/http" "os" + "runtime" "time" "github.com/go-chi/chi" @@ -41,6 +42,7 @@ func NewRouter() *http.Server { r.Mount("/workflows", WorkflowRoutes()) r.Mount("/bounties/ticket", TicketRoutes()) r.Mount("/hivechat", ChatRoutes()) + r.Mount("/test", TestRoutes()) r.Group(func(r chi.Router) { r.Get("/tribe_by_feed", tribeHandlers.GetFirstTribeByFeed) @@ -146,16 +148,29 @@ func getFromAuth(path string) (*extractResponse, error) { func internalServerErrorHandler(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { rr := negroni.NewResponseWriter(w) - next.ServeHTTP(rr, r) - if rr.Status() == http.StatusInternalServerError { - fmt.Printf("Internal Server Error: %s %s\n", r.Method, r.URL.Path) - http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) - } + defer func() { + if err := recover(); err != nil { + // Get stack trace + buf := make([]byte, 4096) + n := runtime.Stack(buf, true) + stackTrace := string(buf[:n]) + + fmt.Printf("Internal Server Error: %s %s\nError: %v\nStack Trace:\n%s\n", + r.Method, + r.URL.Path, + err, + stackTrace, + ) + + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + } + }() + + next.ServeHTTP(rr, r) }) } - func initChi() *chi.Mux { r := chi.NewRouter() r.Use(middleware.RequestID) diff --git a/routes/test_routes.go b/routes/test_routes.go new file mode 100644 index 000000000..92a82b872 --- /dev/null +++ b/routes/test_routes.go @@ -0,0 +1,17 @@ +package routes + +import ( + "net/http" + + "github.com/go-chi/chi" +) + +func TestRoutes() chi.Router { + r := chi.NewRouter() + + r.Get("/internal-server-error", func(w http.ResponseWriter, r *http.Request) { + panic("Forced internal server error") + }) + + return r +}