Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
148: errors.New and Sentinel Errors
I see this all the time in code reviews from developers moving to Go: they try to check for a specific error by recreating that error on the fly. It looks logical at first glance, but in Go, it's a silent bug that will leave you scratching your head when your error handling logic simply never executes.
The "Same Text, Same Error" Fallacy
You might be tempted to write code that looks like this when checking if a user was found in a database:
func GetUser(id string) (*User, error) {
// ... logic to find user ...
return nil, errors.New("user not found")
}
// Later in the calling code...
user, err := GetUser("123")
if err == errors.New("user not found") {
fmt.Println("Handle the missing user case here")
}
You'd expect that because the strings are identical, the == operator would return true. It won't. Every single time you call errors.New, Go allocates a new instance of an error object in memory. You aren't comparing the text of the error; you're comparing the memory addresses of two different objects. They will never be equal, and your "missing user" logic will be completely ignored.
Defining Sentinel Errors for Predictable Failure
To fix this, we use what we call "Sentinel Errors." Instead of creating the error inside the function, I want you to define the error as a package-level variable. This creates a single, unique instance of that error that can be shared across your entire application.
Here is how I actually structure this in production code:
package database
import "errors"
// We name these starting with "Err" by convention.
// This is our Sentinel Error.
var ErrUserNotFound = errors.New("user not found")
func GetUser(id string) (*User, error) {
// ... database logic ...
if notFound {
return nil, ErrUserNotFound // Return the shared instance
}
return user, nil
}
Now, when you call this function, you can compare the returned error against that specific variable. Since both the function and the caller are pointing to the exact same spot in memory, the comparison works perfectly:
user, err := database.GetUser("123")
if err == database.ErrUserNotFound {
// This will actually execute now!
fmt.Println("We need to redirect the user to the signup page.")
}
A quick word of advice: keep your sentinel errors public (capitalized) if you expect users of your package to react to them. If the error is just for internal logging, keep it private. But remember, the moment you find yourself wanting to check if err == someValue, you need a sentinel, not a fresh call to errors.New inside your logic.
📋 Practical Task
Implementing Sentinel Errors for a Digital Wallet
You are building a simple digital wallet system. Currently, the Withdraw function returns generic errors, making it impossible for the UI to tell the difference between a balance issue and a security issue. Your task is to refactor the code to use sentinel errors.
Requirements:
- Define two sentinel errors at the package level:
ErrInsufficientFundsandErrAccountFrozen. - Update the
Withdrawfunction to return these specific sentinel errors instead of creating new ones inside the function. - In the
mainfunction, useif err == ...to print a specific message for each error type.
package main
import (
"errors"
"fmt"
)
// TODO: Define sentinel errors here
type Wallet struct {
Balance float64
Frozen bool
}
func (w *Wallet) Withdraw(amount float64) error {
if w.Frozen {
// TODO: Return the frozen sentinel error
return errors.New("account is frozen")
}
if amount > w.Balance {
// TODO: Return the insufficient funds sentinel error
return errors.New("insufficient funds")
}
w.Balance -= amount
return nil
}
func main() {
myWallet := &Wallet{Balance: 10.00, Frozen: true}
err := myWallet.Withdraw(20.00)
if err != nil {
// TODO: Check for specific sentinel errors and print:
// "Security Alert: Account is frozen!" OR
// "Transaction Failed: Not enough money!"
fmt.Println("Generic error:", err)
}
}There are no comments for now.