27 lines
633 B
Go
27 lines
633 B
Go
|
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||
|
|
|
||
|
|
package middleware
|
||
|
|
|
||
|
|
import (
|
||
|
|
"log/slog"
|
||
|
|
"net/http"
|
||
|
|
"runtime/debug"
|
||
|
|
)
|
||
|
|
|
||
|
|
// Recovery catches panics in HTTP handlers and returns a 500 error
|
||
|
|
// instead of crashing the server.
|
||
|
|
func Recovery(next http.Handler) http.Handler {
|
||
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
|
|
defer func() {
|
||
|
|
if err := recover(); err != nil {
|
||
|
|
slog.Error("panic recovered",
|
||
|
|
"error", err,
|
||
|
|
"path", r.URL.Path,
|
||
|
|
"stack", string(debug.Stack()),
|
||
|
|
)
|
||
|
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||
|
|
}
|
||
|
|
}()
|
||
|
|
next.ServeHTTP(w, r)
|
||
|
|
})
|
||
|
|
}
|