go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/errors/is_panicking.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 "runtime" 18 19 // IsPanicking returns true iff the current goroutine is panicking. 20 // 21 // Always returns false when not invoked via a defer'd function. 22 // 23 // This should only be used to indicate some best-effort error status, not to 24 // modify control flow of the program. Panics are still crashes! 25 // 26 // HACK: Detection is implemented by looking up the stack at most skip+10 frames 27 // above IsPanicking to find if the golang panic handler is on the stack. This 28 // may break when the Go runtime changes! 29 // 30 // `skip` indicates how many additional frames of the stack to skip (a value of 31 // 0 starts the stack at the caller of `IsPanicking`). Clamps to a minimum value 32 // of 0. 33 // 34 // Does NOT invoke `recover()`. WILL detect `panic(nil)`. 35 func IsPanicking(skip int) bool { 36 if skip < 0 { 37 skip = 0 38 } 39 chunk := make([]uintptr, 10) 40 chunk = chunk[:runtime.Callers(2+skip, chunk)] 41 if len(chunk) == 0 { 42 return false 43 } 44 frames := runtime.CallersFrames(chunk) 45 for { 46 frame, more := frames.Next() 47 if frame.Function == "runtime.gopanic" { 48 return true 49 } 50 if !more { 51 return false 52 } 53 } 54 }