forked from pkg/errors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_compehensive_test.go
187 lines (155 loc) · 4.76 KB
/
example_compehensive_test.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
package errors_test
import (
"bytes"
"fmt"
"os"
"github.com/sirupsen/logrus"
. "github.com/pashaosipyants/errors/v2"
"github.com/pashaosipyants/errors/v2/example_auxiliary"
)
// This is comprehensive, pretending to be close to real-life example of using this package.
// It's easier to see it in code, but if you use godoc, please, notice
// https://godoc.org/github.com/pashaosipyants/errors/example_auxiliary package,
// which is used here.
//
// Imagine there is an api to create a task that is executed by another service.
// Besides user of this api wants to hold info whether this task is already done.
// This api, ofc, can return error. E.g. certain task may be already created.
// If so, error should report whether it is done or not.
func Example() {
l := logrus.New().WithField("application", "tasks")
l.Logger.SetFormatter(TerminalVerbose{})
l.Logger.SetOutput(os.Stdout)
// loop to work out different cases
for i := 0; i < 4; i++ {
// func is smth like try block here
func() {
defer l.Infof("\n\tCase %d finished\n-------------------------------------------\n\n\n", i)
// smth like catch block
defer Handler(func(err error) {
switch ValueE(err, "api") {
case errcode_apicreatetaskfailed:
logger, ok := ValueE(err, "logger").(*logrus.Entry) // logger with relevant fields of functions deeper in the call stack
if !ok {
logger = l
}
var ue *UserError
if AsE(err, &ue) {
logger = logger.WithField("user", ue.user)
}
logger.Error(SprintE(err)) // log
// may be some specific actions
case errcode_apiuserloginfailed:
// may be some specific actions
panic("Assertion failed") // but in our example can't be here
default:
panic("Assertion failed")
}
})
Check(
apiUserLogin(l), OValue("api", errcode_apiuserloginfailed))
Check(
apiCreateTask(l, i), OValue("api", errcode_apicreatetaskfailed))
l.Info("Success!!!\n") // log
}()
}
// Output:
// wrong output specially to make this function be executed and see output of this example
}
const errcode_apicreatetaskfailed = "api_create_task_failed"
const errcode_apiuserloginfailed = "api_user_login_failed"
func apiCreateTask(l *logrus.Entry, i int) (reterr error) {
defer Handler(func(err error) {
// do some specific logic - e.g. mark task in db as done
switch {
case IsE(err, example_auxiliary.ErrTaskAlreadyExistButNotDone):
errOnMark := markTaskAsDone()
reterr = AnyE(
WrapE(errOnMark, OSupp(err)),
err,
)
default:
reterr = err
}
// common logic
})
err := example_auxiliary.CreateTaskInitedByUser(l, i, 239)
Check(WrapUserError(err, 239))
return nil
}
// pretends to be always success
func apiUserLogin(l *logrus.Entry) error {
// some work
return nil
}
// pretends that there is an error an task can not be marked as done
func markTaskAsDone() (reterr error) {
defer DefaultHandler(&reterr)
CheckIf(true, Error("task can not be marked as done"))
return
}
func WrapUserError(err error, user int) error {
if err == nil {
return nil
}
return &UserError{
user: user,
err: err,
}
}
type UserError struct {
user int
err error
}
func (x *UserError) Error() string {
return x.err.Error()
}
func (x *UserError) Unwrap() error {
return x.err
}
func (x *UserError) Format(f fmt.State, verb rune) {
if verb == 's' {
fmt.Fprint(f, x.err.Error())
} else {
fmt.Fprintf(f, "User: %d; Error: %v", x.user, x.err)
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////
type TerminalVerbose struct {
}
const breaker = "........................................................\n"
func (t TerminalVerbose) Format(e *logrus.Entry) ([]byte, error) {
if e.Level == logrus.InfoLevel {
msg := lineBreaker(e.Message)
return []byte(msg), nil
}
msg := lineBreaker(e.Message)
var fields string
for k, v := range e.Data {
msg := fmt.Sprint(v)
msg = lineBreaker(msg)
fields += "--" + k + ":\n" + msg
}
var b *bytes.Buffer
if e.Buffer != nil {
b = e.Buffer
} else {
b = &bytes.Buffer{}
}
_, err := b.WriteString("\n" + breaker + msg + "\n" + fields)
if err != nil {
return nil, err
}
return b.Bytes(), nil
}
func lineBreaker(in string) string {
if len(in) > 0 && in[len(in)-1] != '\n' {
in += "\n"
}
return in
}