-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.go
More file actions
50 lines (47 loc) · 1.27 KB
/
utils.go
File metadata and controls
50 lines (47 loc) · 1.27 KB
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
package go_context
import (
"context"
"fmt"
"runtime/debug"
)
// CancelContextOnError cancels the given context if an error is encountered.
//
// Parameters:
//
// ctx: The context to be stopped.
// cancelFn: A function that cancels the context with a given error.
// fn: A function that returns an error.
// loggerProducer: The logger producer to log messages.
//
// Returns:
//
// A function that executes the provided function and cancels the context if an error occurs.
func CancelContextOnError(
ctx context.Context,
cancelFn context.CancelFunc,
fn func(context.Context) error,
) func() error {
return func() (err error) {
// Recover from panic and return as error
defer func() {
if r := recover(); r != nil {
if cancelFn != nil {
cancelFn()
}
switch v := r.(type) {
case error:
err = fmt.Errorf("panic recovered: %w\n%s", v, debug.Stack())
default:
err = fmt.Errorf("panic recovered: %v\n%s", v, debug.Stack())
}
}
}()
if e := fn(ctx); e != nil {
if cancelFn != nil {
cancelFn()
}
return e
}
return nil
}
}