This repository has been archived by the owner on Jul 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
default.go
103 lines (78 loc) · 1.46 KB
/
default.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
93
94
95
96
97
98
99
100
101
102
103
package errors
import (
"errors"
"fmt"
"runtime/debug"
)
type Error struct {
code int
message string
stack string
}
func (e Error) Code() int {
return e.code
}
func (e Error) Error() string {
message := e.message
if e.stack != "" {
message += "\n" + e.stack
}
return message
}
func (e *Error) WithStack() *Error {
e.stack = string(debug.Stack())
return e
}
/**********************************/
func New(message string, code ...int) *Error {
code = sanitizeErrorCode(code...)
return &Error{
code: code[0],
message: message,
}
}
func Newf(message string, v ...any) *Error {
code := make([]int, 0)
if len(v) > 0 {
vcode, ok := v[0].(int)
if ok {
code = append(code, vcode)
}
v = v[1:]
}
message = fmt.Sprintf(message, v...)
return New(message, code...)
}
func From(v any, code ...int) *Error {
var value *Error
switch x := v.(type) {
case *Error:
value = x
if len(code) > 0 {
code = sanitizeErrorCode(code...)
value.code = code[0]
}
case string:
value = New(x, code...)
case error:
value = New(x.Error(), code...)
default:
value = New("An unknown error occurred", 500)
}
return value
}
func Is(err error, target error) bool {
return errors.Is(err, target)
}
func As(err error, target any) bool {
return errors.As(err, target)
}
func sanitizeErrorCode(code ...int) []int {
if len(code) == 0 {
code = append(code, 500)
}
if code[0] == 0 || code[0] == 200 {
code[0] = 500
}
return code
}