Skip to Content
Course content

148: errors.New and Sentinel Errors

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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: ErrInsufficientFunds and ErrAccountFrozen.
  • Update the Withdraw function to return these specific sentinel errors instead of creating new ones inside the function.
  • In the main function, use if 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)
    }
}
Rating
0 0

There are no comments for now.

to be the first to leave a comment.