Skip to content

Commit 150a916

Browse files
committed
fn: add ContextGuard.Goroutine method
Add the ContextGuard.Goroutine method for spawning goroutines within the context guard's scope. This method manages the wait group and ensures consistent error handling for the spawned goroutine via a provided error handler callback. We choose the longer name `Goroutine` rather than `Go` to draw attention to the fact that this function starts a new goroutine.
1 parent 002f4ac commit 150a916

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

fn/context_guard.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,3 +99,29 @@ func (g *ContextGuard) WithCtxQuitNoTimeout() (context.Context, func()) {
9999

100100
return ctx, cancel
101101
}
102+
103+
// Goroutine runs the given function in a separate goroutine and ensures proper
104+
// error handling. If the object function returns an error, the provided error
105+
// handler is called.
106+
//
107+
// This method also manages the context guard wait group when spawning the
108+
// goroutine.
109+
func (g *ContextGuard) Goroutine(f func() error, errHandler func(error)) {
110+
if f == nil {
111+
panic("no function provided")
112+
}
113+
114+
if errHandler == nil {
115+
panic("no error handler provided")
116+
}
117+
118+
g.Wg.Add(1)
119+
go func() {
120+
defer g.Wg.Done()
121+
122+
err := f()
123+
if err != nil {
124+
errHandler(err)
125+
}
126+
}()
127+
}

0 commit comments

Comments
 (0)