Advanced Recovery Patterns
Goroutine Safe Recovery
func safeGoroutine(fn func()) {
defer func() {
if r := recover(); r != nil {
log.Printf("Goroutine panic: %v", r)
}
}()
fn()
}
func main() {
go safeGoroutine(func() {
// Potentially panicking code
})
}
Recovery Strategies
| Pattern | Description | Use Case |
|---------|-------------|----------|
| Centralized Recovery | Global panic handler | Uniform error management |
| Contextual Recovery | Recovery with context | Detailed error tracking |
| Retry Mechanism | Automatic retry on failure | Transient error handling |
Panic Propagation Flow
flowchart TD
A[Panic Occurs] --> B{Recover Available?}
B --> |Yes| C[Handle Locally]
B --> |No| D[Propagate Upwards]
D --> E[Next Defer Handler]
E --> F{Recover Possible?}
F --> |Yes| G[Mitigate Error]
F --> |No| H[Program Terminates]
Contextual Recovery Example
type RecoveryContext struct {
ServiceName string
RequestID string
}
func advancedRecover(ctx RecoveryContext) {
defer func() {
if r := recover(); r != nil {
log.Printf("Service %s, Request %s: Panic recovered - %v",
ctx.ServiceName, ctx.RequestID, r)
// Additional error reporting
}
}()
// Risky operation
}
func transformPanic(err *error) {
if r := recover(); r != nil {
switch x := r.(type) {
case error:
*err = fmt.Errorf("transformed panic: %w", x)
default:
*err = fmt.Errorf("unknown panic: %v", r)
}
}
}
func riskyOperation() (err error) {
defer transformPanic(&err)
// Panic-prone code
return nil
}
LabEx Recommended Practices
At LabEx, we emphasize:
- Granular error handling
- Comprehensive logging
- Minimal performance impact
- Clear error communication
Advanced Goroutine Recovery
func recoverGoRoutine() {
go func() {
defer func() {
if r := recover(); r != nil {
log.Printf("Goroutine recovered: %v", r)
// Optional: restart or notify
}
}()
// Concurrent operation
}()
}
Error Handling Hierarchy
- Prevent panics
- Recover gracefully
- Log comprehensively
- Notify appropriately
- Potentially restart
- Minimize recovery overhead
- Use selective recovery
- Avoid complex recovery logic
- Prefer explicit error handling
Common Advanced Patterns
- Middleware-based recovery
- Circuit breaker implementations
- Distributed error tracking
- Automatic service restoration