Error Handling Patterns
Error Handling Fundamentals
Error handling is a critical aspect of robust Go programming, especially when dealing with process return codes and system interactions.
Basic Error Handling Strategies
1. Simple Error Checking
func executeCommand() error {
cmd := exec.Command("some-command")
if err := cmd.Run(); err != nil {
return fmt.Errorf("command execution failed: %w", err)
}
return nil
}
Error Handling Flow
graph TD
A[Execute Command] --> B{Error Occurred?}
B --> |Yes| C[Log Error]
B --> |No| D[Continue Execution]
C --> E[Handle Error]
E --> F[Retry/Recover/Exit]
Error Handling Patterns
1. Structured Error Handling
type CommandError struct {
Command string
ExitCode int
Err error
}
func (e *CommandError) Error() string {
return fmt.Sprintf("Command %s failed with exit code %d: %v",
e.Command, e.ExitCode, e.Err)
}
func runCommand(command string) error {
cmd := exec.Command("bash", "-c", command)
err := cmd.Run()
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
return &CommandError{
Command: command,
ExitCode: exitErr.ExitCode(),
Err: err,
}
}
return err
}
return nil
}
Error Categorization
Error Type |
Handling Strategy |
Recoverable Errors |
Retry or Alternative Path |
Non-Recoverable Errors |
Graceful Shutdown |
Transient Errors |
Exponential Backoff |
2. Advanced Error Handling
func complexErrorHandling(command string) {
var retries int
for retries < 3 {
err := runCommand(command)
if err == nil {
break
}
switch e := err.(type) {
case *CommandError:
if e.ExitCode == 126 || e.ExitCode == 127 {
log.Printf("Unrecoverable error: %v", err)
break
}
retries++
time.Sleep(time.Second * time.Duration(math.Pow(2, float64(retries))))
default:
log.Printf("Unexpected error: %v", err)
break
}
}
}
Error Handling Best Practices
- Always return errors
- Use custom error types
- Implement meaningful error messages
- Consider error context
- Use error wrapping
LabEx Insight
LabEx provides interactive environments to practice advanced error handling techniques in real-world scenarios.
Conclusion
Effective error handling is not just about catching errors, but understanding and responding to them intelligently.