Skip to content

Instantly share code, notes, and snippets.

@tjs-w
Created January 10, 2016 07:56
Show Gist options
  • Save tjs-w/085de9db4056fd5e5e79 to your computer and use it in GitHub Desktop.
Save tjs-w/085de9db4056fd5e5e79 to your computer and use it in GitHub Desktop.
Golang: Stack Trace on Panic
func stackDump(err *error, f interface{}) {
fname := runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
_, file, line, _ := runtime.Caller(4) // this skips the first 4 that are called under log.Panic()
if r := recover(); r != nil {
fmt.Printf("%s (recover): %v\n", fname, r)
if err != nil {
*err = fmt.Errorf("%v", r)
}
} else if err != nil && *err != nil {
fmt.Printf("%s : %v\n", fname, *err)
}
buf := make([]byte, 1<<10)
runtime.Stack(buf, false)
fmt.Println("==> stack trace: [PANIC:", file, line, fname+"]")
fmt.Println(string(buf))
}
package main
import (
"fmt"
"log"
"os"
"reflect"
"runtime"
"strings"
)
// define func stackDump(err *error, f interface{})
func foo() (err error) {
defer stackDump(&err, foo)
_, err = os.Open("no_such_file.exists")
if err != nil {
log.Panic(err)
}
return err
}
func main() {
foo()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment