In many languages (Java, Python, JavaScript), errors are “exceptions” — they crash the program unless you catch them. In Go, Errors are Values. They are just like int or string. You don’t “throw” them; you pass them around.This philosophy forces you to handle failure cases explicitly where they happen, rather than letting them bubble up and crash your app unexpectedly.
Always use errors.Is() instead of == for error comparison. This handles wrapped errors correctly.
errorhandling/main.go
item, err := findItem(100)if err != nil { // Use errors.Is to check for specific sentinel errors if errors.Is(err, ErrNotFound) { fmt.Println("Search failed: The item does not exist.") } else { fmt.Println("Search failed: Unknown error.") }} else { fmt.Println("Found:", item)}
Analogy: Sentinel errors are like checking a specific HTTP status code (404, 500, etc.).
Sometimes a simple string isn’t enough. You need context: “Which URL failed?”, “How many retries were attempted?”.Custom error types allow you to attach structured data to errors.
type ConnectionError struct { URL string Attempts int}func (e *ConnectionError) Error() string { return fmt.Sprintf("failed to connect to %s after %d attempts", e.URL, e.Attempts)}
1
Step 1: Define the struct
2
Create a struct that holds the additional context you need.
3
Step 2: Implement the Error() method
4
This makes your struct satisfy the error interface.
5
Step 3: Return the custom error
6
Return a pointer to your error struct when the operation fails.
They’re normal return values that must be explicitly checked.
3
Use sentinel errors for simple cases
4
Define error constants with errors.New() and check with errors.Is().
5
Use custom error types for complex cases
6
Create structs that implement the error interface and extract with errors.As().
7
Always check errors immediately
8
Handle errors at the point where they occur, not later.
The Cost of Ignoring Errors: If you don’t check err != nil, Go won’t stop you, but your program will behave unpredictably when failures occur. Silent failures are debugging nightmares.