-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathstatus.go
65 lines (52 loc) · 1.11 KB
/
status.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
package kilonova
import (
"errors"
"fmt"
"log/slog"
)
var (
ErrNoUpdates = Statusf(400, "No updates specified")
ErrMissingRequired = Statusf(400, "Missing required fields")
ErrNotFound = Statusf(404, "Not found")
ErrFeatureDisabled = Statusf(400, "Feature disabled by administrator")
)
var _ error = &statusError{}
type statusError struct {
Code int
Text string
WrappedError error
}
func (s *statusError) LogValue() slog.Value {
if s == nil {
return slog.Value{}
}
return slog.StringValue(s.Text)
}
func (s *statusError) Error() string {
return s.Text
}
func (s *statusError) Unwrap() error {
return s.WrappedError
}
func (s *statusError) Is(target error) bool {
if err, ok := target.(*statusError); ok {
return err.Text == s.Text
}
return false
}
func Statusf(status int, format string, args ...any) error {
if status == 500 {
return fmt.Errorf(format, args...)
}
return &statusError{Code: status, Text: fmt.Sprintf(format, args...)}
}
func ErrorCode(err error) int {
if err == nil {
return 200
}
var sErr *statusError
if errors.As(err, &sErr) {
return sErr.Code
}
return 500
}