Created
January 10, 2016 07:56
-
-
Save tjs-w/085de9db4056fd5e5e79 to your computer and use it in GitHub Desktop.
Golang: Stack Trace on Panic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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