Go•Error Handling
Go Error Handling: if err != nil, fmt.Errorf, and errors.Is
Go treats errors as regular values. Functions return errors explicitly, checked via if err != nil.
Syntax
if err != nil {
return fmt.Errorf("task failed: %w", err)
}
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| %w | Format Verb | Wraps an error in fmt.Errorf for inspection with errors.Is(). |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Go locally:
package main
import (
"errors"
"fmt"
)
var ErrNotFound = errors.New("record not found")
func findUser(id int) (string, error) {
if id != 101 {
return "", fmt.Errorf("query failed for id %d: %w", id, ErrNotFound)
}
return "dev_alex", nil
}
func main() {
// 1. Success query
user, err := findUser(101)
if err == nil {
fmt.Println("Found user:", user)
}
// 2. Failed query with errors.Is check
_, err = findUser(999)
if errors.Is(err, ErrNotFound) {
fmt.Println("[CAUGHT] Verified target error:", err)
}
}Expected Output:
Found user: dev_alex [CAUGHT] Verified target error: query failed for id 999: record not found
How It Works: Step-by-Step
- Line 8: Declares sentinel error ErrNotFound.
- Line 12: Wraps error using fmt.Errorf with %w.
- Lines 25-27: errors.Is detects unwrapped sentinel error.
Key Concepts
- In Go, errors are values of the built-in error interface (Error() string).
- %w wraps errors to retain root cause identity.
- errors.Is unwraps and compares error chains.
Common Mistake: Comparing wrapped errors with == instead of errors.Is
Wrapped errors created with %w are not equal to sentinel errors under ==. Always use errors.Is.
❌ Incorrect
if err == ErrNotFound { /* Fails if err is wrapped! */ }✅ Correct
if errors.Is(err, ErrNotFound) { /* Correctly matches wrapped errors */ }Related Go Tutorials & Compiler
Go Goroutines, Channels, and sync.WaitGroup Concurrency
Master lightweight concurrency in Go using goroutines, channels (<-), and sync.WaitGroup.
Go Multiple Return Values and Error Handling Signatures
Master Go signature multiple return values, named returns, and the idiomatic (result, error) convention without exceptions.
Go Methods and Receiver Functions: OOP Without Classes
Implement OOP methods in Go using value and pointer receivers on structs.
Go Online Compiler
Open in Compilra IDE
Run and test Go on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.