Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch errors from Goroutines?

Tags:

go

I've created function which needs to run in goroutine, the code is working(this is just simple sample to illustrate the issue)

go rze(ftFilePath, 2)


func rze(ftDataPath,duration time.Duration) error {

}

I want to do something like this

errs := make(chan error, 1)
err := go rze(ftFilePath, 2)
if err != nil{
    r <- Result{result, errs}
} 

but not sure how to it, most of the examples show how you do it when you using func https://tour.golang.org/concurrency/5

like image 454
Beno Odr Avatar asked Jul 09 '26 18:07

Beno Odr


2 Answers

You cannot use the return value of a function that is executed with the go keyword. Use an anonymous function instead:

errs := make(chan error, 1)
go func() {
    errs <- rze(ftFilePath, 2)
}()

// later:
if err := <-errs; err != nil {
    // handle error
}
like image 73
Peter Avatar answered Jul 12 '26 09:07

Peter


You can use golang errgroup pkg.

var eg errgroup.Group
eg.Go(func() error {
  return rze(ftFilePath, 2)
})
if err := g.Wait(); err != nil {
    r <- Result{result, errs}
} 
like image 29
Vinay Gupta Avatar answered Jul 12 '26 08:07

Vinay Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!