-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.go
More file actions
79 lines (64 loc) · 1.68 KB
/
Copy pathcode.go
File metadata and controls
79 lines (64 loc) · 1.68 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
75
76
77
78
79
/*
* Copyright (c) 2024 OrigAdmin. All rights reserved.
*/
package errors
import (
"fmt"
"sync"
)
const (
// Deprecated: ErrorCodeSuccess represents a success code. In Go, `nil` is the idiomatic way to indicate success.
// Returning a non-nil error for a successful operation (even with code 0) is an anti-pattern and can lead to incorrect error handling
// with standard `if err != nil` checks. This should be used with caution, primarily at application boundaries (e.g., API responses)
// and not in general business logic. Prefer returning `nil` for success.
ErrorCodeSuccess = ErrorCode(0)
// ErrorCodeError represents a generic error code.
ErrorCodeError = ErrorCode(1)
)
type ErrorCode int
var (
errCodes = map[ErrorCode]string{
ErrorCodeSuccess: "success",
ErrorCodeError: "error",
}
mutCodes = sync.RWMutex{}
)
func RegisterCode(code ErrorCode, val string) {
mutCodes.Lock()
errCodes[code] = val
mutCodes.Unlock()
}
func CodeString(code ErrorCode) string {
mutCodes.RLock()
v, ok := errCodes[code]
mutCodes.RUnlock()
if ok {
return v
}
return fmt.Sprintf("unknown code: %d", code)
}
func (ec ErrorCode) Error() string {
return CodeString(ec)
}
// Is checks if the target error is an ErrorCode and has the same value.
// This allows `errors.Is(wrappedErr, someErrorCode)` to work correctly.
func (ec ErrorCode) Is(err error) bool {
if err == nil {
return false
}
var e ErrorCode
if As(err, &e) {
return e == ec
}
return false
}
func (ec ErrorCode) Code() int {
return int(ec)
}
func (ec ErrorCode) String() string {
return CodeString(ec)
}
// NewCode creates a new ErrorCode from an integer.
func NewCode(code int) ErrorCode {
return ErrorCode(code)
}