Error Handling in Go
The 3 AM Alert That Taught Me Everything
panic: runtime error: invalid memory address or nil pointer dereferencefunc processPayment(orderID string) error {
order := getOrder(orderID) // Returned nil on not found
// Crashed here - didn't check for nil!
amount := order.Total
charge(order.CustomerID, amount)
return nil
}func processPayment(orderID string) error {
order, err := getOrder(orderID)
if err != nil {
return fmt.Errorf("failed to get order %s: %w", orderID, err)
}
if err := charge(order.CustomerID, order.Total); err != nil {
return fmt.Errorf("failed to charge customer: %w", err)
}
return nil
}The Error Interface
Creating Errors
Checking Errors
Error Handling Patterns
Early Return
Handle and Continue
Wrap and Return
Error Wrapping (Go 1.13+)
Why Wrap Errors?
Unwrapping Errors
Custom Error Types
Struct Errors
Real Example: HTTP Errors
Sentinel Errors
Panic and Recover
When to Panic
Recover from Panic
Practical Error Handling Example
Error Handling Best Practices
1. Don't Ignore Errors
2. Add Context When Wrapping
3. Handle Errors at the Right Level
4. Use Custom Error Types for Complex Cases
5. Log and Return
Errors vs Exceptions
Your Challenge
Key Takeaways
What I Learned
Last updated