MCPcopy Index your code
hub / github.com/maruel/panicparse / recoverPanic

Function recoverPanic

stack/example_test.go:236–288  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

234}
235
236func recoverPanic() {
237 if v := recover(); v != nil {
238 // Collect the stack and process it.
239 rawStack := append(debug.Stack(), '\n', '\n')
240 st, _, err := stack.ScanSnapshot(bytes.NewReader(rawStack), io.Discard, stack.DefaultOpts())
241
242 if err != nil || len(st.Goroutines) != 1 {
243 // Processing failed. Print out the raw stack.
244 fmt.Fprintf(os.Stdout, "recovered: %q\nStack processing failed: %v\nRaw stack:\n%s", v, err, rawStack)
245 return
246 }
247
248 // Calculate alignment.
249 srcLen := 0
250 pkgLen := 0
251 for _, line := range st.Goroutines[0].Stack.Calls {
252 if l := len(fmt.Sprintf("%s:%d", line.SrcName, line.Line)); l > srcLen {
253 srcLen = l
254 }
255 if l := len(filepath.Base(line.Func.ImportPath)); l > pkgLen {
256 pkgLen = l
257 }
258 }
259 buf := bytes.Buffer{}
260 // Reduce memory allocation.
261 buf.Grow(len(st.Goroutines[0].Stack.Calls) * (40 + srcLen + pkgLen))
262 for _, line := range st.Goroutines[0].Stack.Calls {
263
264 // REMOVE: Skip the standard library in this test since it would
265 // make it Go version dependent.
266 if line.Location == stack.Stdlib {
267 continue
268 }
269
270 // REMOVE: Not printing args here to make the test deterministic.
271 args := "<args>"
272 //args := line.Args.String()
273
274 fmt.Fprintf(
275 &buf,
276 " %-*s %-*s %s(%s)\n",
277 pkgLen, line.Func.DirName, srcLen,
278 fmt.Sprintf("%s:%d", line.SrcName, line.Line),
279 line.Func.Name,
280 args)
281 }
282 if st.Goroutines[0].Stack.Elided {
283 io.WriteString(&buf, " (...)\n")
284 }
285 // Print out the formatted stack.
286 fmt.Fprintf(os.Stdout, "recovered: %q\nParsed stack:\n%s", v, buf.String())
287 }
288}
289
290// wrapPanic is a http.Handler middleware that traps panics and print it out to
291// os.Stdout.

Callers 1

wrapPanicFunction · 0.85

Calls 3

ScanSnapshotFunction · 0.92
DefaultOptsFunction · 0.92
StringMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…