-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpanic.go
More file actions
74 lines (64 loc) · 1.63 KB
/
panic.go
File metadata and controls
74 lines (64 loc) · 1.63 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package httperror
import (
"errors"
"fmt"
"net/http"
)
var Panic = panicError{}
type panicError struct {
innerError error
message string
}
func (e panicError) Error() string {
if e.innerError != nil {
return "panic: " + e.innerError.Error()
}
return "panic: " + e.message
}
func (e panicError) Unwrap() error {
return e.innerError
}
func (e panicError) Is(other error) bool {
if other == Panic {
return true
}
return errors.Is(e.innerError, other)
}
// PanicMiddleware wraps a [httperror.Handler], returning a new [httperror.HandlerFunc] that
// recovers from panics and returns them as errors. Panic error can be identified using
// errors.Is(err, httperror.Panic)
func PanicMiddleware(h Handler) HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) (err error) {
defer func() {
if r := recover(); r != nil {
isErr := false
if err, isErr = r.(error); !isErr {
err = panicError{nil, fmt.Sprintf("%v", r)}
} else {
err = panicError{err, ""}
}
}
}()
err = h.Serve(w, r)
return
}
}
// XPanicMiddleware wraps a [httperror.XHandler], returning a new [httperror.XHandlerFunc] that
// recovers from panics and returns them as errors. Panic error can be identified using
// errors.Is(err, httperror.Panic)
func XPanicMiddleware[P any](h XHandler[P]) XHandlerFunc[P] {
return func(w http.ResponseWriter, r *http.Request, p P) (err error) {
defer func() {
if r := recover(); r != nil {
isErr := false
if err, isErr = r.(error); !isErr {
err = panicError{nil, fmt.Sprintf("%v", r)}
} else {
err = panicError{err, ""}
}
}
}()
err = h.Serve(w, r, p)
return
}
}