forked from stellar/go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
error.go
92 lines (76 loc) · 2.31 KB
/
error.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
package horizonclient
import (
"encoding/json"
"strings"
hProtocol "github.com/stellar/go/protocols/horizon"
"github.com/stellar/go/support/errors"
"github.com/stellar/go/xdr"
)
func (herr Error) Error() string {
s := strings.Builder{}
s.WriteString(`horizon error: "`)
s.WriteString(herr.Problem.Title)
s.WriteString(`" `)
if rc, err := herr.ResultCodes(); err == nil {
s.WriteString(`(`)
resultCodes := append([]string{rc.TransactionCode}, rc.OperationCodes...)
s.WriteString(strings.Join(resultCodes, `, `))
s.WriteString(`) `)
}
s.WriteString(`- check horizon.Error.Problem for more information`)
return s.String()
}
// Envelope extracts the transaction envelope that triggered this error from the
// extra fields.
func (herr *Error) Envelope() (*xdr.TransactionEnvelope, error) {
b64, err := herr.EnvelopeXDR()
if err != nil {
return nil, err
}
var result xdr.TransactionEnvelope
err = xdr.SafeUnmarshalBase64(b64, &result)
return &result, errors.Wrap(err, "xdr decode failed")
}
// EnvelopeXDR returns the base 64 serialised string representation of the XDR envelope.
// This can be stored, or decoded in the Stellar Laboratory XDR viewer for example.
func (herr *Error) EnvelopeXDR() (string, error) {
raw, ok := herr.Problem.Extras["envelope_xdr"]
if !ok {
return "", ErrEnvelopeNotPopulated
}
var b64 string
b64, ok = raw.(string)
if !ok {
return "", errors.New("type assertion failed")
}
return b64, nil
}
// ResultString extracts the transaction result as a string.
func (herr *Error) ResultString() (string, error) {
raw, ok := herr.Problem.Extras["result_xdr"]
if !ok {
return "", ErrResultNotPopulated
}
b64, ok := raw.(string)
if !ok {
return "", errors.New("type assertion failed")
}
return b64, nil
}
// ResultCodes extracts a result code summary from the error, if possible.
func (herr *Error) ResultCodes() (*hProtocol.TransactionResultCodes, error) {
raw, ok := herr.Problem.Extras["result_codes"]
if !ok {
return nil, ErrResultCodesNotPopulated
}
// converts map to []byte
dataString, err := json.Marshal(raw)
if err != nil {
return nil, errors.Wrap(err, "marshaling failed")
}
var result hProtocol.TransactionResultCodes
if err = json.Unmarshal(dataString, &result); err != nil {
return nil, errors.Wrap(err, "unmarshaling failed")
}
return &result, nil
}