go / expert
Snippet
Selective Panic Recovery and Contextual Error Conversion via Deferred Callbacks
In Go, panics bubble up the stack and crash the process unless trapped with recover() inside a deferred function call. Named return values allow a deferred handler to directly rewrite the outer function's returned error upon recovery. Type switching on the recovered interface value distinguishes standard error types from arbitrary panic values for precise error context wrapping.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package safeexecimport ("fmt")func ExecuteTaskSafely(task func()) (err error) {defer func() {if r := recover(); r != nil {switch e := r.(type) {case error:err = fmt.Errorf("task panicked with error: %w", e)default:err = fmt.Errorf("task panicked with value: %v", e)}}}()task()return nil}
Breakdown
1
func ExecuteTaskSafely(task func()) (err error) {
Uses a named return parameter 'err' so the deferred closure can assign the result after panic intercept.
2
defer func() { ... }()
Registers a deferred function executed automatically during unwinding when the surrounding function finishes or panics.
3
if r := recover(); r != nil {
Traps an active panic, stopping stack unwinding and yielding the interface value passed to panic().
4
switch e := r.(type) {
Performs a dynamic type switch on the panic payload to format typed error wrapping correctly.