Created
April 25, 2024 07:04
-
-
Save ceving/fca0180d7a46ff3491aaaaccf8a11793 to your computer and use it in GitHub Desktop.
Go recover with stack trace
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 ( | |
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