go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/runtime/paniccatcher/catch_test.go (about)

     1  // Copyright 2015 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package paniccatcher
    16  
    17  import (
    18  	"fmt"
    19  	"testing"
    20  
    21  	. "github.com/smartystreets/goconvey/convey"
    22  )
    23  
    24  func TestCatch(t *testing.T) {
    25  	Convey(`Catch will suppress a panic.`, t, func() {
    26  		var pv *Panic
    27  		So(func() {
    28  			defer Catch(func(p *Panic) {
    29  				pv = p
    30  			})
    31  			panic("Everybody panic!")
    32  		}, ShouldNotPanic)
    33  		So(pv, ShouldNotBeNil)
    34  		So(pv.Reason, ShouldEqual, "Everybody panic!")
    35  		So(pv.Stack, ShouldContainSubstring, "TestCatch")
    36  	})
    37  	Convey(`Body does not run with no panic`, t, func() {
    38  		didRun := false
    39  		func() {
    40  			defer Catch(func(*Panic) {
    41  				didRun = true
    42  			})
    43  		}()
    44  		So(didRun, ShouldBeFalse)
    45  	})
    46  }
    47  
    48  // Example is a very simple example of how to use Catch to recover from a panic
    49  // and log its stack trace.
    50  func Example() {
    51  	Do(func() {
    52  		fmt.Println("Doing something...")
    53  		panic("Something wrong happened!")
    54  	}, func(p *Panic) {
    55  		fmt.Println("Caught a panic:", p.Reason)
    56  	})
    57  	// Output: Doing something...
    58  	// Caught a panic: Something wrong happened!
    59  }