Let\'s say I have some code like this:
value, err := some3rdpartylib.DoSomething()
if err != nil {
panic(err)
}
In case err != ni
You can use the built-in Recover function to handle panic and print the stack trace.
From https://blog.golang.org/defer-panic-and-recover
Recover is a built-in function that regains control of a panicking goroutine. Recover is only useful inside deferred functions. During normal execution, a call to recover will return nil and have no other effect. If the current goroutine is panicking, a call to recover will capture the value given to panic and resume normal execution.
I have modified your example to use recover and eris. Eris provides a better way to handle, trace, and log errors in Go.
package main
import (
"github.com/rotisserie/eris"
"fmt"
)
func main() {
value, err := DoSomething()
defer func() {
if r := recover(); r!= nil {
fmt.Println(fmt.Sprintf("%+v", r))
}
}()
if err != nil {
panic(err)
}
fmt.Println(value)
}
func DoSomething() (string, error) {
return "", eris.New("some error explanation here")
}
The output is:
some error explanation here
main.DoSomething: /tmp/sandbox147128055/prog.go: 23
main.main: /tmp/sandbox147128055/prog.go: 9
runtime.main: /usr/local/go/src/runtime/proc.go: 203
runtime.goexit: /usr/local/go/src/runtime/asm_amd64p32.s: 523
See it in action here https://play.golang.org/p/jgkaR42ub5q