~bigbes/huntsman

huntsman/internal/server/middleware/recovery.go -rw-r--r-- 885 bytes
766fa805 — Eugene Blikh Add BSD 2-Clause license 6 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package middleware

import (
	"fmt"
	"log/slog"
	"net/http"

	"go.bigb.es/auxilia/culpa"
	"go.bigb.es/auxilia/scribe"
)

// Recovery catches panics from downstream handlers, logs them with a stack
// trace via culpa, and returns a generic 500 so a single bad handler can't
// crash the process.
func Recovery(logger *slog.Logger) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			defer func() {
				if rec := recover(); rec != nil {
					err, ok := rec.(error)
					if !ok {
						err = fmt.Errorf("%v", rec)
					}
					err = culpa.Wrap(err, "panic recovered")
					logger.Error("panic recovered",
						"path", r.URL.Path,
						scribe.Err(err),
					)
					http.Error(w, "internal server error", http.StatusInternalServerError)
				}
			}()
			next.ServeHTTP(w, r)
		})
	}
}