Skip to content

Commit

Permalink
feat: add stack trace logging for 500 internal server errors
Browse files Browse the repository at this point in the history
  • Loading branch information
aliraza556 committed Dec 16, 2024
1 parent 1eb243c commit af75b81
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
16 changes: 14 additions & 2 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 @@ -145,17 +147,27 @@ func getFromAuth(path string) (*extractResponse, error) {
// Middleware to handle InternalServerError
func internalServerErrorHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("Inside Internal Server Middleware")

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)
// Get stack trace
buf := make([]byte, 1024)
n := runtime.Stack(buf, false)
stackTrace := string(buf[:n])

fmt.Printf("Internal Server Error: %s %s\nStack Trace:\n%s\n",
r.Method,
r.URL.Path,
stackTrace,
)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
})
}


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) {
http.Error(w, "Forced internal server error", http.StatusInternalServerError)
})

return r
}

0 comments on commit af75b81

Please sign in to comment.