How to catch errors from Goroutines?

Viewed 3676

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

3 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
}

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}
} 

You can handle error from go routines using a separate channel for errors. Create a separate channel specifically for errors. Each child go routine must pass corresponding errors into this channel.

This is one of the ways how it can be done:

func main() {
    type err error

    items := []string{"1", "2", "3"}

    ch := make(chan err, len(items))
    for _, f := range items {
        go func(f string) {
            var e err
            e = testFunc(f)
            ch <- e
        }(f)
    }
    for range items {
        e := <-ch
        fmt.Println("Error: ", e)
        if e != nil {
            // DO Something
        }
    }
}

func testFunc(item string) error {
    if item == "1" {
        return errors.New("err")
    }
    return nil
}
Related