-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
92 lines (78 loc) · 2.54 KB
/
errors.go
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package mux
import (
"errors"
"fmt"
"io"
"net/http"
"strings"
)
// ErrorHandler holds resources for returning errors from handlers. If the writer
// is nil, it will not write the error to it. You can use the writer to capture
// a log of errors being returned to the handler. The errFunc uses http.Error if
// no function is provided.
type ErrorHandler struct {
ErrWriter io.Writer
ErrFunc func(w http.ResponseWriter, error string, code int)
}
// ErrHandlerFunc is the function signature for handlers that return an error.
type ErrHandlerFunc func(w http.ResponseWriter, r *http.Request) error
// Err will accept a handler that can return an error and handle it according to
// the errFunc provided or http.Error by default.
func (eh *ErrorHandler) Err(h ErrHandlerFunc) http.Handler {
if eh.ErrFunc == nil {
eh.ErrFunc = http.Error
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err := h(w, r)
if err == nil {
return
}
var e interface{ StatusMsg() (int, string) }
if errors.As(err, &e) {
status, msg := e.StatusMsg()
eh.ErrFunc(w, msg, status)
} else {
eh.ErrFunc(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
if eh.ErrWriter != nil {
fmt.Fprint(eh.ErrWriter, err)
}
})
}
type handlerError struct {
err error
status int
responseMsg string
}
// StatusMsg will return the http status code and message to return to the client.
func (h *handlerError) StatusMsg() (int, string) {
return h.status, h.responseMsg
}
// Error satisfies the error interface
func (h *handlerError) Error() string {
return fmt.Sprintf("status=%d msg=%q err=%q", h.status, h.responseMsg, h.err)
}
// Is reports whether any error in err's tree matches target.
func (h *handlerError) Is(target error) bool {
return errors.Is(h.err, target)
}
// As finds the first error in err's tree that matches target, and if one is
// found, sets target to that error value and returns true. Otherwise, it
// returns false.
func (h *handlerError) As(target any) bool {
return errors.As(h.err, target)
}
// Unwrap returns the underlying error
func (h *handlerError) Unwrap() error {
return h.err
}
// Error will return an error that can be used by the ErrorHandler. The error
// itself is not sent back to the client, but logged instead. The status and
// optional responseMsg are both used to respond to the client.
func Error(err error, status int, responseMsg ...string) error {
return &handlerError{
err: err,
status: status,
responseMsg: strings.Join(responseMsg, " "),
}
}