Error Handling
Error Handling Fundamentals in Golang
Basic Error Concepts
Golang treats errors as values, providing a unique and explicit approach to error management.
Error Interface
type error interface {
Error() string
}
Error Creation and Handling
package main
import (
"errors"
"fmt"
)
func divideNumbers(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
func main() {
result, err := divideNumbers(10, 0)
if err != nil {
fmt.Println("LabEx Error:", err)
}
}
Error Handling Strategies
Error Types
Error Type |
Description |
Example |
Sentinel Errors |
Predefined error values |
io.EOF |
Custom Errors |
User-defined error types |
Custom struct implementing error |
Wrapped Errors |
Errors with additional context |
fmt.Errorf() |
Error Flow Visualization
graph TD
A[Function Call] --> B{Error Occurred?}
B --> |Yes| C[Error Handling]
B --> |No| D[Continue Execution]
C --> E[Log Error]
C --> F[Return Error]
C --> G[Retry/Recover]
Advanced Error Handling Techniques
Custom Error Types
type ValidationError struct {
Field string
Message string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("Validation error in %s: %s", e.Field, e.Message)
}
Error Wrapping
func processData(data string) error {
if err := validateInput(data); err != nil {
return fmt.Errorf("data processing failed: %w", err)
}
return nil
}
Error Handling Patterns
Defer, Panic, and Recover
func recoverFromPanic() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}()
panic("unexpected error")
}
Error Handling Best Practices
- Return errors explicitly
- Use meaningful error messages
- Avoid ignoring errors
- Use error wrapping for context
- Create custom error types when necessary
Error Checking Strategies
Multiple Error Checks
func complexOperation() error {
if err := step1(); err != nil {
return fmt.Errorf("step 1 failed: %w", err)
}
if err := step2(); err != nil {
return fmt.Errorf("step 2 failed: %w", err)
}
return nil
}
graph LR
A[Error Handling] --> B[Minimal Overhead]
A --> C[Explicit Error Management]
A --> D[Predictable Execution]
Conclusion
Effective error handling in Golang requires a systematic approach, combining explicit error checking, meaningful error messages, and strategic error management techniques.