From 78664cbf1ab89d853d8d6e182c20a9857adcbec4 Mon Sep 17 00:00:00 2001 From: kevkevinpal Date: Fri, 6 Dec 2024 11:47:00 -0500 Subject: [PATCH] feat: added middleware to catch when there is an internal server error --- routes/index.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/routes/index.go b/routes/index.go index 8da500084..505d89799 100644 --- a/routes/index.go +++ b/routes/index.go @@ -140,11 +140,36 @@ func getFromAuth(path string) (*extractResponse, error) { }, nil } +// Middleware to handle InternalServerError +func internalServerErrorHandler(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + rr := &responseRecorder{ResponseWriter: w, statusCode: http.StatusOK} + next.ServeHTTP(rr, r) + + if rr.statusCode == http.StatusInternalServerError { + fmt.Printf("Internal Server Error: %s %s\n", r.Method, r.URL.Path) + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + } + }) +} + +// Custom ResponseWriter to capture status codes +type responseRecorder struct { + http.ResponseWriter + statusCode int +} + +func (rr *responseRecorder) WriteHeader(code int) { + rr.statusCode = code + rr.ResponseWriter.WriteHeader(code) +} + func initChi() *chi.Mux { r := chi.NewRouter() r.Use(middleware.RequestID) r.Use(middleware.Logger) r.Use(middleware.Recoverer) + r.Use(internalServerErrorHandler) cors := cors.New(cors.Options{ AllowedOrigins: []string{"*"}, AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},