I have a goroutine with logic:
result1, err := getResult1()
result2, err := getResult2(result)
result3, err := getResult3(result2)
If I have an error in getResult1(), I would not like to continue this goroutine at all, but no panic, because it destroy the main too. I've implemented it in an awful way, but what would be the idiomatic solution?
CodePudding user response:
The idiomátic way is do something
r, err := get()
if err != nil {
// do something with err
// do not continue
}
…
You can return the error to the caller, and the caller decide what to do.
You don’t need to panic. You can just log.
Or use the error in some loop to retry
CodePudding user response:
In golang it's better to handle errors as soon as they occur
result1, err := getResult1()
if err != nil {
// log your error and return
return err
}
result2, err := getResult2(result)
result3, err := getResult3(result2)
If you need to handle panics and regain control over panicking goroutine, then recover() is your way to go:
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovering my panicing goroutine", r)
}
}()