Add recovery middleware to handle panics and log errors

This commit is contained in:
2025-04-20 23:45:44 -05:00
parent bd455f1782
commit 9fd027fcda
2 changed files with 29 additions and 1 deletions

View File

@ -0,0 +1,27 @@
package middleware
import (
"log"
"net/http"
"runtime/debug"
)
// Recovery middleware to catch panics, log them, and return a 500 error
func Recovery() Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
// Log the stack trace
log.Printf("PANIC: %v\n%s", err, debug.Stack())
// Return a 500 Internal Server Error response
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Internal Server Error"))
}
}()
next.ServeHTTP(w, r)
})
}
}