Sławosz
Sławosz

Reputation: 11687

Hijacking panic output

When my golang app is panicking, it is printing go routines stack trace and quiting. I wonder if there is nice way to get panic output for further processing. Redirecting stderr is not enough, because one would like to put some error logs there. I would like to get only panic output.

Upvotes: 1

Views: 98

Answers (2)

Specode
Specode

Reputation: 1023

    1 package main
    2 
    3 import (
    4 ›   "fmt"
    5 )
    6 
    7 func main() {
    8 ›   defer func() {
    9 ›   ›   if r := recover(); r != nil {
   10 ›   ›   ›   fmt.Println("panic:", r)                                                                                                                                                                                                 
   11 ›   ›   }
   12 ›   }()
   13 
   14 ›   test := []int{1, 2, 3}
   15 ›   fmt.Println(test[5])
   16 
   17 }

using defer and recover.

http://blog.golang.org/defer-panic-and-recover

Upvotes: 0

James Henstridge
James Henstridge

Reputation: 43899

You can get a formatted stack trace using the runtime.Stack function. By passing true as the second argument, you can see stack traces of all gouroutines.

Upvotes: 2

Related Questions