Error Handling Techniques
Fundamental Error Handling in Type Conversion
Basic Error Checking
func safeStringToInt(s string) (int, error) {
value, err := strconv.Atoi(s)
if err != nil {
return 0, fmt.Errorf("conversion failed: %v", err)
}
return value, nil
}
Error Handling Strategies
flowchart TD
A[Type Conversion Error Handling] --> B[Explicit Error Checking]
A --> C[Panic and Recover]
A --> D[Custom Error Types]
B --> E[Return Error]
C --> F[Controlled Panic]
D --> G[Custom Error Implementation]
Comprehensive Error Handling Patterns
Multiple Error Scenarios
func robustConversion(input string) {
// Scenario 1: Simple conversion
value, err := strconv.Atoi(input)
switch {
case err == nil:
fmt.Println("Successful conversion:", value)
case err != nil:
handleConversionError(err)
}
}
func handleConversionError(err error) {
switch {
case errors.Is(err, strconv.ErrSyntax):
fmt.Println("Invalid syntax")
case errors.Is(err, strconv.ErrRange):
fmt.Println("Value out of range")
default:
fmt.Println("Unknown conversion error")
}
}
Error Handling Techniques Comparison
Technique |
Pros |
Cons |
Best Used When |
Explicit Error Return |
Clear error handling |
Requires explicit checks |
Most scenarios |
Panic/Recover |
Stops execution |
Can crash program |
Critical failures |
Custom Error Types |
Detailed error information |
More complex |
Complex error scenarios |
Advanced Error Handling
Custom Error Types
type ConversionError struct {
Value string
Type string
Message string
}
func (e *ConversionError) Error() string {
return fmt.Sprintf("conversion error: cannot convert %s to %s - %s",
e.Value, e.Type, e.Message)
}
Safe Conversion Wrapper
func safeConvert[T any](value interface{}, converter func(interface{}) (T, error)) (T, error) {
result, err := converter(value)
if err != nil {
var zero T
return zero, fmt.Errorf("safe conversion failed: %v", err)
}
return result, nil
}
Error Handling Best Practices
- Always check conversion errors
- Use meaningful error messages
- Provide context in error handling
- Prefer returning errors over panicking
- Use type assertions carefully
Logging and Monitoring
func logConversionError(err error) {
log.Printf("Conversion error occurred: %v", err)
// Potential integration with monitoring systems
}
Note: When practicing error handling techniques, LabEx provides an interactive environment for exploring Go's robust error management capabilities.