-
Notifications
You must be signed in to change notification settings - Fork 1
/
httperr.go
80 lines (62 loc) · 1.18 KB
/
httperr.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
package httperr
import (
"net/http"
"github.com/pkg/errors"
)
type StatusCoder interface {
StatusCode() int
}
func ErrCode(err error) int {
var sc StatusCoder
if errors.As(err, &sc) {
return sc.StatusCode()
}
return 500
}
// WriteErr writes the error code.
func WriteErr(w http.ResponseWriter, err error) {
w.WriteHeader(ErrCode(err))
}
type basicError struct {
code int
msg string
}
var (
_ error = (*basicError)(nil)
_ StatusCoder = (*basicError)(nil)
)
func New(code int, msg string) error {
return basicError{code, msg}
}
func (e basicError) Error() string {
return e.msg
}
func (e basicError) StatusCode() int {
return e.code
}
type wrapError struct {
code int
wrap error
}
var (
_ error = (*wrapError)(nil)
_ StatusCoder = (*wrapError)(nil)
)
func Wrap(err error, code int, msg string) error {
if err == nil {
return nil
}
return wrapError{code, errors.Wrap(err, msg)}
}
func Wrapf(err error, code int, f string, v ...interface{}) error {
if err == nil {
return nil
}
return wrapError{code, errors.Wrapf(err, f, v...)}
}
func (e wrapError) Error() string {
return e.wrap.Error()
}
func (e wrapError) StatusCode() int {
return e.code
}