Error Handling
Errors as Values
Go does not have exceptions. Instead, functions that can fail return an error value alongside their result. This is arguably Go's most important design decision.
The error Interface
The built-in error type is an interface with a single method:
type error interface {
Error() string
}
Any type that has an Error() string method is an error. This is the simplest possible contract.
Creating Errors
The standard library provides two ways to create simple errors:
import "errors"
err := errors.New("something went wrong")
import "fmt"
err := fmt.Errorf("user %s not found", username)
fmt.Errorf works like fmt.Sprintf but returns an error. Use it when you need formatted messages.
The Error-Checking Pattern
The canonical Go pattern: call a function, check the error immediately, handle it or return it:
result, err := doSomething()
if err != nil {
return fmt.Errorf("doSomething failed: %w", err)
}
// use result
The %w verb wraps the original error, preserving the chain for debugging. This pattern appears hundreds of times in any real Go codebase.
"He's dead, Jim." Dr. McCoy never threw an exception --- he returned a clear error status. Go handles errors the same way: no drama, just values.
Custom Error Types
For richer error information, define your own error type:
type ValidationError struct {
Field string
Message string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("%s: %s", e.Field, e.Message)
}
When to Return Errors
A function should return an error when:
- An operation can fail (file I/O, network, parsing)
- The failure is recoverable (the caller can do something about it)
- The failure is expected in normal operation
Do not return errors for programming mistakes (like passing a nil pointer where one is never expected). Use panics for those.
Your Task
Write a function validateAge that takes an int and returns an error:
- If age is negative, return an error with the message
"age cannot be negative" - If age is greater than 150, return an error with the message
"age is unrealistic" - Otherwise, return
nil(no error)