How does try
work with call chains across goroutines?
#15
Replies: 1 comment
-
Thank you for your excellent comment and feedback! I'm sorry for the unclear documentation. The root cause for misleading documentation was to forget to mention that each of the goroutines has its own stacks and, naturally, own calls stacks. And it's true that every goroutine's 'root function' like However, with the help of func main() {
defer err2.Catch()
go func() {
defer err2.Catch()
// Only a recover in the same goroutine can catch a panic
panic("Oops")
}()
time.Sleep(1 * time.Second)
println("\n\n----- main end's ok")
} The playground to the above code. The sample below tries to illustrate the original idea behind the 'misleading' documentation: package main
import (
"github.com/lainio/err2"
"github.com/lainio/err2/try"
)
// recursiveFn is a sample of a complex recursive algorithm where
// errors/exceptions are transported as panics, i.e., non-local control flow.
func recursiveFn(x int) (y int) {
if x == 10 {
err2.Throwf("error TEN") // <==> panic(fmt.Errorf("error TEN"))
}
if x == 0 {
return 0
}
return x + recursiveFn(x-1)
}
// fn is a wrapper with the help of err2 to be used without panics.
// could be the exported (public) function, i.e., pkg API.
func fn(x int) (y int, err error) {
defer err2.Handle(&err)
return recursiveFn(x), nil
}
func main() {
defer err2.Catch()
println("recursiveFn(4):", recursiveFn(4))
println("recursiveFn(7):", recursiveFn(7))
//println("recursiveFn(17):", recursiveFn(17))
println("fn(4):", try.To1(fn(4)))
println("fn(7):", try.To1(fn(7)))
println("fn(17):", try.To1(fn(17)))
println("\n\n----- never here")
} The playground. I hope that especially the playground shows the strength of I recommend testing the assertion package, which also works for tests and runtime asserts. Naturally, automatic error traces are very convenient as well. The |
Beta Was this translation helpful? Give feedback.
-
The documentation says that
defer
-ing theHandle
call can happen anywhere up the stack trace. While true, this isn't entirely correct when talking about multiple goroutines. Even if you try to recover from a panic as high up as themain
function, if a separate goroutine panics and goes unhandled, this will still crash the entire app.Beta Was this translation helpful? Give feedback.
All reactions