By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
Go does not have exceptions. A function that can fail returns an error as its last result, and the caller checks it. That is the whole mechanism, and it keeps the failure path visible in the code you are reading.
error is a built-in interface with one method: Error() string. Anything with that method is an error value, including types you write yourself. The standard library gives you two ways to make one: errors.New for a fixed message, and fmt.Errorf for a formatted message.
A sentinel error is a package-level error value created once and compared against many times. Give it a name that starts with Err, keep it exported if callers need it, and never build a new error with the same text.
package main
import (
"errors"
"fmt"
)
// ErrInvalidAmount is a sentinel: one value, compared in many places.
var ErrInvalidAmount = errors.New("amount must be greater than zero")
func validateCents(cents int) error {
if cents <= 0 {
return ErrInvalidAmount
}
return nil
}
func main() {
err := validateCents(0)
if errors.Is(err, ErrInvalidAmount) {
fmt.Println("rejected:", err)
}
if err := validateCents(450); err == nil {
fmt.Println("450 cents is valid")
}
}A nil error means success. Always check if err != nil before using the other results, and always return nil when nothing went wrong.
%wA bare sentinel tells the caller what went wrong but not where. fmt.Errorf with the %w verb builds a new error that adds context and keeps the original inside so errors.Is can still find it later. The w stands for wrap.
package main
import (
"errors"
"fmt"
)
var ErrEmptyDescription = errors.New("description is empty")
func buildExpense(description string, cents int) error {
if description == "" {
return ErrEmptyDescription
}
return nil
}
func addExpense(description string, cents int) error {
if err := buildExpense(description, cents); err != nil {
return fmt.Errorf("add expense: %w", err)
}
return nil
}
func main() {
err := addExpense("", 450)
fmt.Println("error:", err)
fmt.Println("caused by an empty description?", errors.Is(err, ErrEmptyDescription))
fmt.Println("valid expense failed?", addExpense("Coffee", 450) != nil)
}Compare the two verbs. %w wraps and keeps the error for errors.Is and errors.As. %v only formats its text, which is right when the original error is not something a caller should inspect - but most of the time you want %w.
errors.Is and errors.Aserrors.Is(err, target) answers: is this error, or any error wrapped inside it, equal to target? Use it with sentinel errors. errors.As(err, &target) answers a different question: does the chain contain a value of this type, and if so, put it in target? Use it when the error carries data, such as the line number that failed to parse.
| Tool | Use it when | Example |
|---|---|---|
errors.New | You need a fixed sentinel cause | var ErrNoAmount = errors.New("no amount") |
fmt.Errorf with %w | You add context and keep identity | fmt.Errorf("add expense: %w", err) |
errors.Is | You ask if a specific cause is in the chain | errors.Is(err, ErrNoAmount) |
errors.As | You need a custom error type and its data | var parseErr *ParseError; errors.As(err, &parseErr) |
Good Go error handling has a simple shape. Check the error, return it with context, and keep the successful path flat along the left edge of the function. This pattern is called a guard clause, and it removes deep nesting from the code that follows.
else block wrapping the rest.fmt.Errorf("load expenses: %w", err) says what you were doing.Penny stores money as integer cents. The command line gives dollars as text, so dollarsToCents parses it, rounds to the nearest cent, and rejects zero or negative amounts. Each layer wraps with its own context.
package main
import (
"errors"
"fmt"
"math"
"strconv"
)
type Expense struct {
ID int
Description string
Cents int
}
// ErrInvalidAmount marks every bad amount Penny rejects.
var ErrInvalidAmount = errors.New("invalid amount")
func dollarsToCents(input string) (int, error) {
value, err := strconv.ParseFloat(input, 64)
if err != nil {
return 0, fmt.Errorf("parse %q: %w", input, ErrInvalidAmount)
}
cents := int(math.Round(value * 100))
if cents <= 0 {
return 0, fmt.Errorf("%q: %w", input, ErrInvalidAmount)
}
return cents, nil
}
func newExpense(id int, description, amount string) (Expense, error) {
cents, err := dollarsToCents(amount)
if err != nil {
return Expense{}, fmt.Errorf("new expense %q: %w", description, err)
}
return Expense{ID: id, Description: description, Cents: cents}, nil
}
func main() {
expense, err := newExpense(1, "Coffee", "12.50")
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("added #%d: %s costs %d cents\n", expense.ID, expense.Description, expense.Cents)
_, err = newExpense(2, "Refund", "-3.00")
fmt.Println("refund error:", err)
fmt.Println("invalid amount?", errors.Is(err, ErrInvalidAmount))
_, err = newExpense(3, "Snack", "abc")
fmt.Println("snack error:", err)
fmt.Println("invalid amount?", errors.Is(err, ErrInvalidAmount))
}Notice that the happy path is five lines and the failure paths return immediately. Notice also that the caller never inspects the message text; it asks errors.Is about the sentinel. That is the habit that keeps code working when messages change.
Add a second sentinel, ErrTooLarge, and reject amounts above 1000000 cents (that is $10000.00). Wrap it from dollarsToCents, then check errors.Is(err, ErrTooLarge) in main for the input "20000.00". Then print the full error to see the chain of context your wrapping produced.
Key takeaways
Go errors are values: error is an interface with one method, Error() string.
errors.New makes a fixed sentinel error; compare with errors.Is, not == or strings.
fmt.Errorf with %w adds context and keeps the original error inside the chain.
errors.Is walks a wrapped chain; errors.As extracts a typed error from it.
Return early, wrap once per layer, and never compare error messages.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.