-
Notifications
You must be signed in to change notification settings - Fork 14
/
marshaling.go
116 lines (103 loc) · 2.47 KB
/
marshaling.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
104
105
106
107
108
109
110
111
112
113
114
115
116
package terrors
import (
pe "github.com/monzo/terrors/proto"
"github.com/monzo/terrors/stack"
)
// Marshal an error into a protobuf for transmission
func Marshal(e *Error) *pe.Error {
// Account for nil errors
if e == nil {
return &pe.Error{
Code: ErrUnknown,
Message: "Unknown error, nil error marshalled",
}
}
retryable := &pe.BoolValue{}
if e.IsRetryable != nil {
retryable.Value = *e.IsRetryable
}
unexpected := &pe.BoolValue{}
if e.IsUnexpected != nil {
unexpected.Value = *e.IsUnexpected
}
err := &pe.Error{
Code: e.Code,
Message: e.Message,
MessageChain: e.MessageChain,
Stack: stackToProto(e.StackFrames),
Params: e.Params,
Retryable: retryable,
Unexpected: unexpected,
MarshalCount: int32(e.MarshalCount + 1),
}
if err.Code == "" {
err.Code = ErrUnknown
}
return err
}
// Unmarshal a protobuf error into a local error
func Unmarshal(p *pe.Error) *Error {
if p == nil {
return &Error{
Code: ErrUnknown,
Message: "Nil error unmarshalled!",
Params: map[string]string{},
}
}
var retryable *bool
if p.Retryable != nil {
retryable = &p.Retryable.Value
}
var unexpected *bool
if p.Unexpected != nil {
unexpected = &p.Unexpected.Value
}
err := &Error{
Code: p.Code,
Message: p.Message,
MessageChain: p.MessageChain,
StackFrames: protoToStack(p.Stack),
Params: p.Params,
IsRetryable: retryable,
IsUnexpected: unexpected,
MarshalCount: int(p.MarshalCount),
}
if err.Code == "" {
err.Code = ErrUnknown
}
// empty map[string]string come out as nil. thanks proto.
if err.Params == nil {
err.Params = map[string]string{}
}
return err
}
// protoToStack converts a slice of *pe.StackFrame and returns a stack.Stack
func protoToStack(protoStack []*pe.StackFrame) stack.Stack {
if protoStack == nil {
return stack.Stack{}
}
s := make(stack.Stack, 0, len(protoStack))
for _, frame := range protoStack {
s = append(s, &stack.Frame{
Filename: frame.Filename,
Method: frame.Method,
Line: int(frame.Line),
})
}
return s
}
// stackToProto converts a stack.Stack and returns a slice of *pe.StackFrame
func stackToProto(s stack.Stack) []*pe.StackFrame {
if s == nil {
return []*pe.StackFrame{}
}
protoStack := make([]*pe.StackFrame, 0, len(s))
for _, frame := range s {
protoStack = append(protoStack, &pe.StackFrame{
Filename: frame.Filename,
Line: int32(frame.Line),
Method: frame.Method,
})
}
return protoStack
}