Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: modfied action to take log and save it when error #2129

Merged
merged 1 commit into from
Dec 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions routes/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"},
Expand Down
Loading