如何从 Goroutines 中捕获错误?

Ben*_*Odr 0 go

我创建了需要在 goroutine 中运行的函数,代码正在运行(这只是说明问题的简单示例)

go rze(ftFilePath, 2)


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

}
Run Code Online (Sandbox Code Playgroud)

我想做这样的事情

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

但不确定如何操作,大多数示例都展示了使用https://tour.golang.org/concurrency/5时如何操作func

Vin*_*pta 7

您可以使用 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}
} 
Run Code Online (Sandbox Code Playgroud)


Pet*_*ter 5

您不能使用使用 go 关键字执行的函数的返回值。改用匿名函数:

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

// later:
if err := <-errs; err != nil {
    // handle error
}
Run Code Online (Sandbox Code Playgroud)