github.com/sandwich-go/boost@v1.3.29/xpanic/catch_test.go (about) 1 package xpanic 2 3 import ( 4 "fmt" 5 "testing" 6 7 . "github.com/smartystreets/goconvey/convey" 8 ) 9 10 func TestCatch(t *testing.T) { 11 Convey(`Catch will suppress a panic.`, t, func() { 12 var pv *Panic 13 So(func() { 14 defer Catch(func(p *Panic) { 15 pv = p 16 }) 17 panic("Everybody panic!") 18 }, ShouldNotPanic) 19 20 So(pv, ShouldNotBeNil) 21 So(pv.Reason, ShouldEqual, "Everybody panic!") 22 }) 23 } 24 25 // Example is a very simple example of how to use Catch to recover from a panic 26 // and log its stack trace. 27 func Example() { 28 Do(func() { 29 fmt.Println("Doing something...") 30 panic("Something wrong happened!") 31 }, func(p *Panic) { 32 fmt.Println("Caught a panic:", p.Reason) 33 }) 34 // Output: Doing something... 35 // Caught a panic: Something wrong happened! 36 }