-
Notifications
You must be signed in to change notification settings - Fork 0
/
try.go
59 lines (51 loc) · 1.09 KB
/
try.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
/*
* Copyright (c) 2024 Mikhail Knyazhev <[email protected]>. All rights reserved.
* Use of this source code is governed by a BSD 3-Clause license that can be found in the LICENSE file.
*/
package do
import "fmt"
func Try(try func(), catch func(err error), finally func()) {
if try != nil {
err := Recovery(try)
if err != nil && catch != nil {
//nolint:errcheck
_ = Recovery(func() {
catch(err)
})
}
}
if finally != nil {
//nolint:errcheck
_ = Recovery(finally)
}
}
type (
StepByStep[V any] struct {
steps []func(V) (V, error)
}
)
func NewStepByStep[V any]() *StepByStep[V] {
return &StepByStep[V]{
steps: make([]func(V) (V, error), 0),
}
}
func (v *StepByStep[V]) Add(fn func(V) (V, error)) {
v.steps = append(v.steps, fn)
}
func (v *StepByStep[V]) Exec(value V) (val V, err error) {
val = value
for i, step := range v.steps {
e := Recovery(func() {
val, err = step(val)
})
if e != nil {
err = fmt.Errorf("panic on step #%d: %w", i+1, e)
return
}
if err != nil {
err = fmt.Errorf("fail on step #%d: %w", i+1, err)
return
}
}
return
}