forked from thockin/go-build-template
/
error.go
116 lines (98 loc) · 2.03 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
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 error
import (
"fmt"
"io/ioutil"
"strconv"
"gopkg.in/yaml.v2"
)
type AppError struct {
Code int
Message string
Cause error
Action string
}
type TransientError struct {
Code int
Message string
Cause error
RetryCount int
}
type DefinedErrors struct {
// Name string `yaml:name`
// Detail Detail `yaml:detail`
Errors map[string]Detail `yaml:"errors,omitempty"`
}
type Detail struct {
Code int `yaml:"code"`
Action string `yaml:"action,omitempty"`
Transient bool `yaml:"transient"`
}
func buildString(code int, message string, cause error) (e string) {
if code != 0 {
e = e + strconv.Itoa(code)
}
if message != "" {
if len(e) > 0 {
e = e + " "
}
e = e + message
}
if cause != nil {
if len(e) > 0 {
e = e + " "
}
e = e + "cause: " + cause.Error()
}
return
}
func (ae *AppError) Error() string {
var e string
// build error string based provided info
e = buildString(ae.Code, ae.Message, ae.Cause)
// add corrective action if provided
if ae.Action != "" {
if len(e) > 0 {
e = e + " "
}
e = e + "corrective action: " + ae.Action
}
return e
}
func (te *TransientError) Error() string {
var e string
// build error string based provided info
e = buildString(te.Code, te.Message, te.Cause)
// add corrective action if provided
if te.RetryCount > 0 {
if len(e) > 0 {
e = e + " "
}
e = e + "retry count: " + strconv.Itoa(te.RetryCount)
}
return e
}
func (de *DefinedErrors) Load() error {
var err error
//load only once
if len(de.Errors) > 0 {
//quit early,
return err
}
// read in the error yaml
f, err := ioutil.ReadFile("errors.yml")
if err != nil {
fmt.Println("warning: no defined errors detected")
return err
}
fmt.Println("YAML FILE:\n" + string(f))
// if successful, marshall errors into Defined errors
me := make(map[string]Detail)
err = yaml.Unmarshal(f, &me)
if err != nil {
fmt.Println("warning: defined errors detected, but unreadable")
return err
}
fmt.Printf("YAML Struct:\n%+v", me)
de.Errors = me
return err
}