-
Notifications
You must be signed in to change notification settings - Fork 2
/
error_handler.go
68 lines (63 loc) · 2.32 KB
/
error_handler.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
package mq
import (
"context"
"fmt"
)
type ErrorMessage struct {
Field string `yaml:"field" mapstructure:"field" json:"field,omitempty" gorm:"column:field" bson:"field,omitempty" dynamodbav:"field,omitempty" firestore:"field,omitempty"`
Code string `yaml:"code" mapstructure:"code" json:"code,omitempty" gorm:"column:code" bson:"code,omitempty" dynamodbav:"code,omitempty" firestore:"code,omitempty"`
Param string `yaml:"param" mapstructure:"param" json:"param,omitempty" gorm:"column:param" bson:"param,omitempty" dynamodbav:"param,omitempty" firestore:"param,omitempty"`
Message string `yaml:"message" mapstructure:"message" json:"message,omitempty" gorm:"column:message" bson:"message,omitempty" dynamodbav:"message,omitempty" firestore:"message,omitempty"`
}
func NewErrorHandler[T any](logError ...func(context.Context, string)) *ErrorHandler[T] {
h := &ErrorHandler[T]{}
if len(logError) >= 1 {
h.LogError = logError[0]
}
return h
}
type ErrorHandler[T any] struct {
LogError func(context.Context, string)
}
func (w *ErrorHandler[T]) Reject(ctx context.Context, res T, err []ErrorMessage, data []byte) {
if w.LogError != nil && data != nil {
w.LogError(ctx, fmt.Sprintf("Message is invalid %s Error: %+v", data, err))
}
}
func (w *ErrorHandler[T]) RejectWithMap(ctx context.Context, res T, err []ErrorMessage, data []byte, attrs map[string]string) {
if w.LogError != nil && data != nil {
if len(attrs) > 0 {
w.LogError(ctx, fmt.Sprintf("Message is invalid %s Attributes: %+v Error: %+v", data, attrs, err))
} else {
w.LogError(ctx, fmt.Sprintf("Message is invalid %s Error: %+v", data, err))
}
}
}
func (w *ErrorHandler[T]) HandleError(ctx context.Context, data []byte) {
if w.LogError != nil && data != nil {
w.LogError(ctx, fmt.Sprintf("Message is invalid %s", data))
}
}
func (w *ErrorHandler[T]) HandleErrorWithMap(ctx context.Context, data []byte, attrs map[string]string) {
if w.LogError != nil && data != nil {
if len(attrs) > 0 {
w.LogError(ctx, fmt.Sprintf("Message is invalid %s Attributes: %+v", data, attrs))
} else {
w.LogError(ctx, fmt.Sprintf("Message is invalid %s", data))
}
}
}
func GetString(ctx context.Context, key string) string {
if len(key) > 0 {
u := ctx.Value(key)
if u != nil {
s, ok := u.(string)
if ok {
return s
} else {
return ""
}
}
}
return ""
}