/
try.go
106 lines (90 loc) · 2.52 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
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
// Copyright (c) 2024 Proton AG
//
// This file is part of Proton Mail Bridge.
//
// Proton Mail Bridge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Proton Mail Bridge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Proton Mail Bridge. If not, see <https://www.gnu.org/licenses/>.
package try
import (
"fmt"
"sync"
"github.com/ProtonMail/gluon/async"
"github.com/bradenaw/juniper/xerrors"
"github.com/sirupsen/logrus"
)
// Catch tries to execute the `try` function, and if it fails or panics,
// it executes the `handlers` functions in order.
func Catch(try func() error, handlers ...func() error) error {
if _, err := CatchVal(func() (any, error) { return nil, try() }, handlers...); err != nil {
return err
}
return nil
}
// CatchVal tries to execute the `try` function, and if it fails or panics,
// it executes the `handlers` functions in order.
func CatchVal[T any](try func() (T, error), handlers ...func() error) (res T, err error) {
defer func() {
if r := recover(); r != nil {
catch(handlers...)
err = xerrors.WithStack(fmt.Errorf("panic: %v", r))
}
}()
if res, err = try(); err != nil {
catch(handlers...)
return res, err
}
return res, nil
}
func catch(handlers ...func() error) {
defer func() {
if r := recover(); r != nil {
logrus.WithError(xerrors.WithStack(fmt.Errorf("panic: %v", r))).Error("Catch handler panicked")
}
}()
for _, handler := range handlers {
if err := handler(); err != nil {
logrus.WithError(err).Error("Catch handler failed")
}
}
}
type Group struct {
mu sync.Mutex
panicHandler async.PanicHandler
}
func MakeGroup(panicHandler async.PanicHandler) Group {
return Group{panicHandler: panicHandler}
}
func (wg *Group) GoTry(fn func(bool)) {
if wg.mu.TryLock() {
go func() {
defer async.HandlePanic(wg.panicHandler)
defer wg.mu.Unlock()
fn(true)
}()
} else {
go func() {
defer async.HandlePanic(wg.panicHandler)
fn(false)
}()
}
}
func (wg *Group) Lock() {
wg.mu.Lock()
}
func (wg *Group) Unlock() {
wg.mu.Unlock()
}
func (wg *Group) Wait() {
wg.mu.Lock()
defer wg.mu.Unlock()
}