Skip to content

Instantly share code, notes, and snippets.

@ceving
Created April 25, 2024 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ceving/fca0180d7a46ff3491aaaaccf8a11793 to your computer and use it in GitHub Desktop.
Save ceving/fca0180d7a46ff3491aaaaccf8a11793 to your computer and use it in GitHub Desktop.
Go recover with stack trace
package main
import (
dbg "runtime/debug"
fmt "fmt"
os "os"
tm "time"
)
func outer() {
inner(42)
}
func inner(i int) {
var a [1]byte
a[i] = 42
}
func RecoverWithStackTrace() {
if r := recover(); r != nil {
fmt.Fprintf(os.Stderr, "\f%s %+v\n\n",
tm.Now().Format(tm.RFC3339Nano), r)
dbg.PrintStack()
}
}
func main() {
defer RecoverWithStackTrace()
outer()
}
// Local Variables:
// compile-command: "go run recover.go"
// End:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment