Error Handling
Error Handling Strategies in Go
Go provides multiple approaches to handle errors effectively, focusing on explicit error checking and management.
Error Types and Patterns
graph TD
A[Error Handling] --> B[Built-in Error Interface]
A --> C[Custom Error Types]
A --> D[Error Wrapping]
Error Interface in Go
type error interface {
Error() string
}
Error Handling Techniques
Technique |
Description |
Example |
Explicit Checking |
Direct error validation |
if err != nil { ... } |
Custom Error Types |
Create domain-specific errors |
type ValidationError struct {} |
Error Wrapping |
Add context to errors |
fmt.Errorf("operation failed: %w", err) |
Comprehensive Error Handling Example
package main
import (
"errors"
"fmt"
"log"
)
type CustomError struct {
Message string
Code int
}
func (e *CustomError) Error() string {
return fmt.Sprintf("Error %d: %s", e.Code, e.Message)
}
func riskyOperation() error {
// Simulating an error condition
return &CustomError{
Message: "Operation not permitted",
Code: 403,
}
}
func main() {
err := riskyOperation()
if err != nil {
switch e := err.(type) {
case *CustomError:
log.Printf("Custom error: %v", e)
default:
log.Printf("Unknown error: %v", err)
}
}
}
Advanced Error Handling Techniques
Error Wrapping
func processData(data []byte) error {
if len(data) == 0 {
return fmt.Errorf("invalid data: %w", errors.New("empty input"))
}
return nil
}
Best Practices
- Always return and check errors
- Use custom error types for specific scenarios
- Provide meaningful error messages
- Use error wrapping to add context
At LabEx, we recommend comprehensive error handling to create robust and maintainable Go applications.