How to handle the errors in the go routine

In my code , I have a function which is getting data from the database for different ids , so i put in the go routine for each id , but in case if any go routine face any error then how it will be handled .I stuck on it .

Below is the snippet:

func BStat(ID string) (t []string, err error) {

var wg sync.WaitGroup
var e error

ch1 := make(chan string)
ch2 := make(chan error)
defer close(ch1)
defer close(ch2)


for i:=0 ; i <10 :i++  {
	wg.Add(1)
	go GetStat(ID, ch1, ch2 , &wg)
}

for i:=0 ; i <10 :i++{
	e = <- ch2
	if e != nil {                                               // How to Handle error 
		fmt.Println("Heloooooooooooooooo")
		break
		//return nil, errors.New("error in generating report ")
	}
	
	Stat, ok := <-ch1
	if ok == true {
			t = append(t, Stat)
		}
	}

 wg.Done()

return t, e

}

func GetStat( Id uint64, ch1 chan<- []string , ch2 chan<- bool , wg *sync.WaitGroup) {

stat, err := store.GetName(db, i)    // Value from the db 
if err != nil {
			logger.WithError(err)
			ch2 <- true
			ch1 <- ""
}
ch2 <- false
ch1 <- stat

}

My go routine stuck , Please suggest me how to handle the o/p and to handle the error case .

Thanks In Advance

I’m having a hard time understanding the code. I started by putting it into the Go Playground but it won’t build: https://play.golang.org/p/mYwthC8_qxj

Based on the parameters you’re calling GetStat with (not the parameters GetStat accepts), it looks like GetStat should read its inputs from ch1 and write any errors it receives into ch2.

Hey Sean ,

Here is the link of the compiled code.
https://play.golang.org/p/ZQYNZ702y7h

Currently it is working but sometime it gives me error that I am sending on the closed channel when I put greater than 2 in ch2

In General , What if multiple goroutines write to the same channel? If one goroutine has done its work it can’t simply close the channel. Other goroutines may still need to write to the channel

Please suggest whether the way/pattern in which i have written this code is correct or there is a scope of improvement .

Thanks in Advance

you can use errgroup

https://pkg.go.dev/golang.org/x/sync/errgroup?tab=doc

1 Like

Thanks Ryze, will look into this

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.