My Go function is expected to return a value, but it may panic when calling a library function. I can use recover()
to capture this in a deferred call, but how can I return a value in this case?
func MyFunc() string{
defer func() {
if err := recover(); err != nil {
// What do I do to make MyFunc() return a value in case of panic?
}
}()
SomeFuncThatMayPanic()
return "Normal Return Value"
// How can I return "ERROR" in case of panic?
}
You can use named result parameters. Name your return values, and in the deferred function when panic was detected, you can change the values of the return "variables". The changed new values will be returned.
Example:
Output (try it on the Go Playground):
This is mentioned in the Spec: Defer statements:
It is also mentioned in the blog post Defer, Panic and Recover:
And also in Effective Go: Recover: