go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/errors/is_panicking_example_test.go (about)

     1  // Copyright 2020 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 errors
    16  
    17  import (
    18  	"fmt"
    19  	"runtime/debug"
    20  	"strings"
    21  )
    22  
    23  func CrashingFunction() {
    24  	panic("boom")
    25  }
    26  
    27  func ExampleIsPanicking() {
    28  	A := func(crash bool) {
    29  		defer func() {
    30  			if IsPanicking(0) {
    31  				fmt.Println("PANIK!")
    32  			} else {
    33  				fmt.Println("kalm")
    34  			}
    35  		}()
    36  		if crash {
    37  			fmt.Println("about to boom")
    38  			CrashingFunction()
    39  		} else {
    40  			fmt.Println("smooth sailing")
    41  		}
    42  	}
    43  
    44  	defer func() {
    45  		// Make sure IsPanicking didn't do a `recover()`, which would goof up the
    46  		// stack.
    47  		stack := string(debug.Stack())
    48  		if !strings.Contains(stack, "CrashingFunction") {
    49  			fmt.Println("stack trace doesn't originate from CrashingFunction")
    50  		} else {
    51  			fmt.Println("stack trace originates from CrashingFunction")
    52  		}
    53  		// But recover ourselves to make sure ExampleIsPanicking actually passes
    54  		// instead of crashing with an unrecovered panic.
    55  		recover()
    56  	}()
    57  
    58  	if IsPanicking(0) {
    59  		fmt.Println("cannot be panicing when not in defer'd function.")
    60  	}
    61  
    62  	A(false)
    63  	fmt.Println("first pass success")
    64  	A(true)
    65  
    66  	// Output:
    67  	// smooth sailing
    68  	// kalm
    69  	// first pass success
    70  	// about to boom
    71  	// PANIK!
    72  	// stack trace originates from CrashingFunction
    73  }