Error Handling in Go
Go takes a unique approach to error handling. Instead of exceptions, Go uses explicit error values that must be checked. This makes error handling visible and forces you to think about what happens when things go wrong. The Go philosophy:- Errors are values - they’re returned like any other value
- Handle errors explicitly - no hidden control flow
- Panic for truly exceptional cases - not for normal error handling
The error Interface
The built-inerror interface is simple:
Error Interface
Error() string method implements the error interface.
Basic Error Handling
The convention is to return errors as the last return value. A nil error indicates success.
Creating Errors
There are several ways to create errors:- errors.New
- fmt.Errorf
- Custom Errors
Simple Errors
Error Wrapping and Unwrapping
Go 1.13+ introduced error wrapping to preserve error chains:Error Wrapping
- Use
%winfmt.Errorfto wrap errors - Use
errors.Isto check if an error is or wraps a specific error - Use
errors.Asto check if an error is or wraps a specific type
Defer Statement
Thedefer keyword schedules a function call to run after the surrounding function returns. Deferred calls run in LIFO (Last In, First Out) order.
Basic Defer Usage
Defer Basics
Defer Stack
Defer Order
Defer for Resource Cleanup
Panic and Recover
panic and recover are Go’s mechanisms for handling truly exceptional situations - things that shouldn’t happen in normal program flow.
When to Panic
Use panic for:- Programming errors (nil pointer, out of bounds)
- Unrecoverable situations (can’t initialize critical resources)
- Violations of invariants
- Normal error handling
- Validation errors
- Expected failures
Panic Example
Using Panic
Recover from Panic
recover can catch a panic, but only when called inside a deferred function:
Recovering from Panic
Real-World Example: Image Detector
Here’s a complete example showing error handling, defer, panic, and recover:Error Handling Patterns
Early Return
Early Return
Handle errors immediately and return early:This keeps the happy path on the left and errors handled immediately.
Early Return Pattern
Error Aggregation
Error Aggregation
Collect multiple errors:
Multiple Errors
Sentinel Errors
Sentinel Errors
Define package-level error variables for common errors:
Sentinel Errors
Best Practices
Always Check Errors
Never ignore returned errors. If you truly want to ignore an error, be explicit:
Use Defer for Cleanup
Always use defer for cleanup operations like closing files, unlocking mutexes, etc.
Common Mistakes
Testing Error Handling
Error Testing
Related Topics
Interfaces
The error interface and custom errors
Functions
Multiple return values for errors
Defer, Panic, Recover
Deep dive into error recovery
Testing
Testing error conditions