-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathCustomError.go
82 lines (67 loc) · 1.78 KB
/
CustomError.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
package error
import (
"errors"
"fmt"
errorsPkg "github.com/pkg/errors"
"strings"
)
type CustomError struct {
errorCode ErrorCode
errorMsg string
error error
exists bool
loggingParams map[string]interface{}
}
func NewCustomError(errorCode ErrorCode, error string) CustomError {
c := CustomError{errorCode: errorCode, errorMsg: error, exists: true}
e := errors.New(fmt.Sprintf("Code: %s | %s", c.errorCode, c.errorMsg))
c.error = errorsPkg.WithStack(e)
c.loggingParams = make(map[string]interface{}, 0)
return c
}
func (c CustomError) Exists() bool {
return c.exists
}
func (c CustomError) Log() {
fmt.Println(c.ToString())
}
func (c CustomError) LoggingParams() map[string]interface{} {
return c.loggingParams
}
func (c CustomError) ErrorCode() ErrorCode {
return c.errorCode
}
func (c CustomError) ToError() error {
return c.error
}
func (c CustomError) Error() string {
return c.error.Error()
}
func (c CustomError) ErrorMessage() string {
return c.errorMsg
}
func (c CustomError) ToString() string {
logMsg := fmt.Sprintf("Code: %s, Msg: %s", c.errorCode, c.errorMsg)
paramStrings := make([]string, 0)
for key, val := range c.loggingParams {
paramStrings = append(paramStrings, fmt.Sprintf("%s: {%+v}", strings.ToUpper(key), val))
}
return fmt.Sprintf("%s, Params: [%+v]", logMsg, strings.Join(paramStrings, " | "))
}
// value param should not be a pointer
func (c CustomError) WithParam(key string, val interface{}) CustomError {
if c.loggingParams == nil {
c.loggingParams = make(map[string]interface{}, 0)
}
c.loggingParams[key] = val
return c
}
func (c CustomError) ErrorString() string {
return c.errorMsg
}
func (c CustomError) UserMessage() string {
if val, found := ErrorCodeToUserMessages[c.errorCode]; found {
return val
}
return ""
}