I have the following code:
package main
import (
"fmt"
)
func recoverFoo() {
if r := recover(); r != nil {
println("Recovered")
}
}
func foo() (int, error) {
defer recoverFoo()
panic("shit!")
}
func main() {
x, err := foo()
println("after foo x = " + fmt.Sprint(x))
if err != nil {
println("An error occured")
} else {
println("No error occured")
}
}
In this situtation, I am calling foo (in reality my function foo is calling a third party library which sometimes panics, but also sometimes return err). If it panics I can't have it crashing the app, but I need to know something went wrong as I have to write to local storage on error.
In this case though the value x returned from Foo can have a valid value of 0. So the recovery setting x and err to their defaults (0 and nil), doesn't tell me if an error actually occurred...
I see two possible solutions, (1) I wrap the err and x into a custom return type and assume if its nil then an error occurred. (2) I have a third return boolean that specifies a panic didn't occur (it will default to false)
Is their something I'm missing here around go error handling and recovering from panics. I'm new to go so would like some advice.