Skip to content

Commit

Permalink
Add stack trace logging for internal server errors (500) (#2204)
Browse files Browse the repository at this point in the history
* feat: add stack trace logging for 500 internal server errors

* remove unnecessarily comment

* feat: Implement stack trace capture for 500 errors
  • Loading branch information
aliraza556 authored Dec 17, 2024
1 parent 4960625 commit e5fcf13
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 6 deletions.
27 changes: 21 additions & 6 deletions routes/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"io"
"net/http"
"os"
"runtime"
"time"

"github.com/go-chi/chi"
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
17 changes: 17 additions & 0 deletions routes/test_routes.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit e5fcf13

Please sign in to comment.