These are the notes for Go episode 24. Episode 23 ended with Raju typing a dish that isn't on his menu: what should price("dosa") return? Many languages answer with exceptions: a special mechanism that jumps out of the function and up the call stack until some catch block grabs it. Go has no exceptions. Instead it has one of its most famous ideas, and in this episode you will invent it yourself: errors are ordinary values. You will see why magic values like 0 and -1 (also called in-band signals) lie, then give a function a second result of type error, returned last, with the zero value beside it. You will make errors with errors.New, check them with if err != nil, and see Go refuse to let you forget one (declared and not used: err). You will learn what the built-in error interface really is, add details with fmt.Errorf, compare sentinel errors like ErrNotOnMenu and io.EOF with ==, build custom error types that carry data, fall into (and climb out of) the typed-nil trap, and follow Go's message conventions: lowercase, no ending punctuation. The mini project bills order lines with fmt.Sscan and strconv.Atoi. The expert corner opens up *errors.errorString, explains why errors.New returns a pointer, reads the standard library's own errors (*fs.PathError, *strconv.NumError), and shows a few sharp edges. Every example runs as-is in the SyntaxPilot compiler (language: Go); outputs, compiler errors and panics are from real runs of go run main.go (Go 1.24, linux/amd64). Panic traces show /tmp/.../main.go where the real temporary folder was, and the +0x... numbers differ between machines and runs.
The problem: what should price("dosa") return?
Raju's menu is a map from item name to price (episode 15). price looks an item up with the comma-ok form p, ok := menu[item]: ok is true when the key exists and false when it doesn't (then p is the zero value, 0). The obvious question is what to return when ok is false.
- Returning
0puts a free dosa on the bill. - So someone returns
-1and adds a comment: "-1 means not found". Three items, one missing:
package main
import "fmt"
var menu = map[string]float64{"chai": 10, "samosa": 15}
func price(item string) float64 {
p, ok := menu[item]
if !ok {
return -1 // "not found"?
}
return p
}
func main() {
var total float64
for _, it := range []string{"chai", "dosa", "samosa"} {
total += price(it)
}
fmt.Println("Total:", total)
}
Total: 24
Total: 24. The real answer is "25 for chai and samosa, and dosa is not on the menu". Instead-1was quietly added like any other price. No crash, no warning: just a wrong bill.- A special return value that secretly means "it failed" is called a magic value (magic because you have to know the secret meaning) or an in-band signal. "In band" means the failure signal travels in the same channel as the real data:
-1is a perfectly good float64, so nothing stops the caller from using it as a price. C'sgetcharreturningEOF(usually-1) at the end of input and Java'sindexOfreturning-1are famous examples. - The real problem: one result can't carry both "the price" and "the news that something went wrong". We need a second channel: an out-of-band signal, separate from the data.
A second result: the error
Think of a shop counter.
| At the counter | In Go | Name |
|---|---|---|
| You get your chai, and no slip | return 10, nil |
success: the value, and a nil error |
| No dosa: you get a slip saying "not on menu" | return 0, errors.New("item not on menu") |
failure: the zero value, and an error that says why |
| You read the slip before you try to eat | if err != nil { ... } |
the caller checks first, then uses the value |
nilis Go's word for "nothing here": the zero value of pointers, slices, maps, channels, functions and interfaces (episode 11, episode 21). For an error,nilmeans no error.- The zero value of a type is the value a variable has before you assign anything (episode 3):
0for numbers,""for strings,nilfor pointers. When a function fails, it returns the zero value for its other results, as a polite "this is meaningless, don't use it".
package main
import (
"errors"
"fmt"
)
var menu = map[string]float64{"chai": 10, "samosa": 15}
func price(item string) (float64, error) {
p, ok := menu[item]
if !ok {
return 0, errors.New("item not on menu")
}
return p, nil
}
func main() {
for _, it := range []string{"chai", "dosa"} {
p, err := price(it)
if err != nil {
fmt.Println(it, "->", err)
continue
}
fmt.Println(it, "->", p)
}
}
chai -> 10
dosa -> item not on menu
func price(item string) (float64, error)has two results (multiple return values, episode 9).erroris a built-in type: no import needed for the type itself.- The error is always the last result. This is a convention (an agreed habit, not a compiler rule), but the whole standard library and every Go codebase follow it:
strconv.Atoi(s) (int, error),os.Open(name) (*os.File, error),fmt.Println(...) (n int, err error). A function that can fail but has nothing else to return has just one result,error. errors.New("item not on menu"), from the standarderrorspackage, makes a new error whose message is that text. That's why the file now imports"errors".- On failure:
return 0, errors.New(...)(zero value + error). On success:return p, nil(value + nil error). - The caller writes
if err != nil("if there is an error"): handle it, thencontinuethe loop. Only after the check does it usep. chai -> 10anddosa -> item not on menu: the failure can no longer be mistaken for a price. You just invented Go's error handling.
if err != nil, early returns and the happy path
The shape you just wrote is everywhere in Go: call, x, err := f(...); check, if err != nil { ... } (handle it, or return it to your own caller); then use x.
Two words you'll hear about it:
- The happy path is the code that runs when everything goes right: no errors, no special cases.
- An early return means leaving a function as soon as something fails, instead of wrapping the rest of the function in an
else. Go style: check each failure, return early, and keep the happy path at the left margin, unindented, so you can read it top to bottom.
Here is the same function written nested and flat (with menu as before, importing errors and fmt):
// nested: the real work drifts to the right
func costNested(item string, qty int) (float64, error) {
if qty > 0 {
if p, ok := menu[item]; ok {
return p * float64(qty), nil
} else {
return 0, errors.New("item not on menu")
}
} else {
return 0, errors.New("quantity must be positive")
}
}
// flat: check, return early, the happy path stays on the left
func cost(item string, qty int) (float64, error) {
if qty <= 0 {
return 0, errors.New("quantity must be positive")
}
p, ok := menu[item]
if !ok {
return 0, errors.New("item not on menu")
}
return p * float64(qty), nil
}
func main() {
fmt.Println(costNested("chai", 2))
fmt.Println(cost("chai", 2))
fmt.Println(cost("chai", 0))
fmt.Println(cost("dosa", 1))
}
20 <nil>
20 <nil>
0 quantity must be positive
0 item not on menu
- Both give
20 <nil>for two chai (fmt.Printlnprints both results; a nil error prints as<nil>). IncostNestedthe real work is buried two levels deep, and the error for the first check is at the bottom. Incosteach check sits right next to the thing it checks. - People call
if err != nilverbose, and it is. But nothing is hidden: every place that can fail is visible, and the reader sees exactly what happens next. With exceptions, any line might secretly jump somewhere else.
Can you just ignore an error?
What if we call price and never look at err?
package main
import (
"errors"
"fmt"
)
var menu = map[string]float64{"chai": 10, "samosa": 15}
func price(item string) (float64, error) {
p, ok := menu[item]
if !ok {
return 0, errors.New("item not on menu")
}
return p, nil
}
func main() {
p, err := price("dosa")
fmt.Println(p)
}
# command-line-arguments
./main.go:19:8: declared and not used: err
declared and not used: err: Go's unused-variable rule (episode 3) catches the forgotten check. It isn't an error-specific rule, but it means you can't accidentally drop an error you named.- You can still throw it away on purpose with the blank identifier
_, a write-only name that discards a value (episode 3). With the samemenuandprice:
func main() {
p, _ := price("dosa") // error thrown away on purpose
fmt.Println(p)
}
0
- It compiles and prints
0, the meaningless zero value. Now the choice is visible in the code: anyone reviewing it sees_where an error should be. Do this only when failure really can't matter (and say why in a comment). - Calling
priceand ignoring both results (price("dosa")as a statement) also compiles. Linters such aserrcheckflag ignored error results; the compiler doesn't.
The error interface: what is an error, really?
Recall episode 22: error is a built-in interface type (an interface lists method signatures; any type with those methods satisfies it, episode 21). It has exactly one method:
type error interface {
Error() string
}
- It is predeclared: built into the language like
intandstring, so you never import it. - Any type with an
Error() stringmethod is an error. Noimplementskeyword needed. - The zero value of every interface is
nil, so a variablevar err errorstarts asnil: "no error". - When
fmt.Println(err)(or%v,%s) gets an error, it callserr.Error()to get the message. That's whydosa -> item not on menuprinted the text. err != nilis simply the nil-interface check from episode 21: is there anything in the box?
fmt.Errorf: errors with details
item not on menu doesn't say which item. fmt.Errorf works exactly like fmt.Sprintf (episode 18: build a string from a format and values) but returns an error instead of a string. %q prints a string in double quotes. We also print the error's dynamic type (the concrete type inside the interface, episode 21) with %T, and a nil error.
package main
import "fmt"
var menu = map[string]float64{"chai": 10, "samosa": 15}
func price(item string) (float64, error) {
p, ok := menu[item]
if !ok {
return 0, fmt.Errorf("%q is not on the menu (%d items)", item, len(menu))
}
return p, nil
}
func main() {
_, err := price("dosa")
fmt.Println(err)
fmt.Printf("%T\n", err)
var e error
fmt.Println(e == nil, e)
}
"dosa" is not on the menu (2 items)
*errors.errorString
true <nil>
"dosa" is not on the menu (2 items): the message now carries the item and the menu size.%dwithlen(menu)works like in any Printf.*errors.errorString: the concrete type inside is a pointer to a tiny struct callederrorStringinside theerrorspackage.errors.Newreturns one, and so doesfmt.Errorfwhen its format has no%w(that verb is next episode). The expert corner shows what's inside.true <nil>: a nil error equalsnil, and prints as<nil>.
Errors are values: sentinel errors
"Errors are values" is a Go saying: an error isn't a special control-flow event, it's an ordinary value, like an int or a string. You can store it in a variable, pass it to a function, put it in a slice, return it, and compare it with ==.
| Printed slips at the counter | In Go | Name |
|---|---|---|
| A pre-printed slip: "SHOP CLOSED" | var ErrClosed = errors.New("shop is closed") |
a sentinel error: one fixed error value |
| You recognise it at a glance, no need to read it | if err == ErrClosed { ... } |
compare with ==, react to which error |
| An "End of book" page: not bad news at all | io.EOF |
a sentinel that means finished, not failed |
- A sentinel is a guard posted to stand for one thing. A sentinel error is one error value, created once and stored in a package-level variable (declared outside any function, so the whole package, and other packages if exported, can use it). By convention its name starts with
Err:ErrNotOnMenu,io.ErrUnexpectedEOF,os.ErrNotExist(io.EOFis the famous exception to the naming rule). - Callers compare against that one variable to find out what kind of failure happened, without reading the message text.
package main
import (
"errors"
"fmt"
)
var ErrNotOnMenu = errors.New("item not on menu")
var ErrClosed = errors.New("shop is closed")
var menu = map[string]float64{"chai": 10, "samosa": 15}
func price(item string, hour int) (float64, error) {
if hour < 7 || hour > 22 {
return 0, ErrClosed
}
p, ok := menu[item]
if !ok {
return 0, ErrNotOnMenu
}
return p, nil
}
func main() {
_, err := price("dosa", 10)
if err == ErrNotOnMenu {
fmt.Println("suggest: chai or samosa")
}
_, err = price("chai", 23)
if err == ErrClosed {
fmt.Println("come back at 7")
}
fmt.Println(errors.New("a") == errors.New("a"))
}
suggest: chai or samosa
come back at 7
false
suggest: chai or samosaandcome back at 7: the caller reacted differently to each sentinel.false!errors.Newreturns a new, distinct value every time, even with the same text. Two errors are==only when they are the very same value (for*errors.errorString: the same pointer). That's exactly why a sentinel is created once, in a variable, and everyone compares against that variable.- Never compare messages (
err.Error() == "item not on menu"): someone fixes a typo in the text and your check silently stops working.
io.EOF: the sentinel that means "finished"
EOF stands for end of file: there's nothing more to read. io.EOF (in package io, short for input/output) is the most famous sentinel in Go. strings.NewReader("chai") makes a reader over a string (a strings.Reader; readers come back in episode 33), and ReadByte returns one byte at a time, plus an error.
package main
import (
"fmt"
"io"
"strings"
)
// io.EOF: the sentinel for "nothing left"
func main() {
r := strings.NewReader("chai")
for {
b, err := r.ReadByte()
if err == io.EOF {
fmt.Println("| done:", err)
break
}
fmt.Printf("%c ", b)
}
}
c h a i | done: EOF
c h a i, then| done: EOF. When nothing is left,ReadBytereturnsio.EOF, whose message is justEOF.- Here the "error" isn't a failure at all: it's how the reader says "I'm finished". Errors are values, and you decide what each one means. Reading to the end is normal; any other error would be a real problem (practice 3 checks both).
Custom error types: errors that carry data
A message is just text. But the caller may need data: how many samosas are left, so it can offer that many instead? Make a type. Any type with an Error() string method is an error, so a struct can be one.
package main
import "fmt"
type OutOfStock struct {
Item string
Left int
}
func (e *OutOfStock) Error() string {
return fmt.Sprintf("%s out of stock (%d left)", e.Item, e.Left)
}
func order(item string, qty int) error {
left := 3 // samosas left today
if qty > left {
return &OutOfStock{item, left}
}
return nil
}
func main() {
err := order("samosa", 5)
fmt.Println(err)
if e, ok := err.(*OutOfStock); ok {
fmt.Println("offer", e.Left, "instead of 5")
}
fmt.Println(order("samosa", 2))
}
samosa out of stock (3 left)
offer 3 instead of 5
<nil>
OutOfStockis a struct withItemandLeft.*OutOfStock(a pointer, episode 11) has theErrormethod, so&OutOfStock{...}satisfieserror.orderreturns just anerror, since it has no other result.samosa out of stock (3 left):PrintlncalledError(), which built the message from the fields.err.(*OutOfStock)is a type assertion (episode 22): "I think the concrete type inside this interface is*OutOfStock; give it to me". The comma-ok forme, ok := ...doesn't crash when it's something else;okis justfalse. Withewe reade.Left:offer 3 instead of 5.<nil>: the successful order returned a nil error.- Convention: custom error type names end in
Error(*fs.PathError,*strconv.NumError,*json.SyntaxError), and sentinel variable names start withErr.OutOfStockbreaks the first rule to keep the video short;LineErrorin the extended mini project follows it. - Pointer or value receiver? Most custom errors use a pointer receiver and are returned as
&T{...}. Then returning the plain value doesn't compile:
# command-line-arguments
./main.go:11:16: cannot use OutOfStock{…} (value of struct type OutOfStock) as error value in return statement: OutOfStock does not implement error (method Error has pointer receiver)
- (Real run:
orderreturningOutOfStock{"samosa"}without&, line 11.) Same rule as episode 21's method sets: a pointer-receiverErroris only in*OutOfStock's method set.
The typed-nil trap
Episode 21 warned about this, and with errors it bites for real. check starts with e, a nil *OutOfStock, sets it only for big orders, and returns e as an error. We order 2, which is fine.
package main
import "fmt"
type OutOfStock struct{ Item string }
func (e *OutOfStock) Error() string { return e.Item + " out of stock" }
func check(qty int) error {
var e *OutOfStock // nil
if qty > 3 {
e = &OutOfStock{"samosa"}
}
return e // a nil *OutOfStock inside an error
}
func main() {
err := check(2)
if err != nil {
fmt.Printf("failed? %T %v\n", err, err == nil)
}
}
failed? *main.OutOfStock false
failed?was printed:err != nilwas true, although nothing went wrong!%Tshows*main.OutOfStock, anderr == nilisfalse.- An interface value is a pair (dynamic type, dynamic value) and is nil only when both are nil (episode 21). Returning
eput the type*OutOfStockin the box with a nil pointer inside. That is a typed nil: a nil pointer wrapped in a non-nil interface. - The fix: when there's no error,
return nil(a literal nil), never a nil pointer variable.
With the same OutOfStock, check fixed, and a main that tries 2 and 5:
func check(qty int) error {
if qty > 3 {
return &OutOfStock{"samosa"}
}
return nil // a truly nil error
}
func main() {
for _, q := range []int{2, 5} {
err := check(q)
fmt.Printf("%d: %T %v %v\n", q, err, err == nil, err)
}
}
2: <nil> true <nil>
5: *main.OutOfStock false samosa out of stock
2: <nil> true <nil>: a truly nil error.5:gets the real*main.OutOfStock.- Same rule for helper functions: declare their result as
error, not*OutOfStock.func check() *OutOfStockreturning nil is fine on its own, but the moment the caller writesvar err error = check(), the trap is back.
Error message conventions
Last, style. price returns "Item not on menu.", with a capital I and a full stop. bill adds context (where the error happened: which order) with fmt.Errorf("order %d: %v", order, err), and main adds its own prefix.
package main
import (
"errors"
"fmt"
)
func price(item string) (float64, error) {
return 0, errors.New("Item not on menu.")
}
func bill(order int) error {
_, err := price("dosa")
if err != nil {
return fmt.Errorf("order %d: %v", order, err)
}
return nil
}
func main() {
err := bill(7)
fmt.Println("billing failed:", err)
}
billing failed: order 7: Item not on menu.
billing failed: order 7: Item not on menu.: a capital letter in the middle of a sentence, and a full stop before nothing. Error messages are joined like this all the time, each caller addingsomething:in front.- So Go's convention (from the official Go Code Review Comments): error strings start lowercase (unless they begin with a proper noun or acronym like
URLorGo), have no ending punctuation (no.or!), and contain no newlines. Linters enforce it:staticcheckreports it as check ST1005. The compiler doesn't care. - With
errors.New("item not on menu")the same program printsbilling failed: order 7: item not on menu, which reads as one clean line. - Good messages also say what failed and which thing:
"dosa" not on menubeatsnot found. Prefix with the operation (open menu.txt: ...), not with "error:" or "failed to" (the caller already knows it failed).
The standard library follows the same style; you'll see it in every error in the expert corner.
Mini project: bill a list of order lines
Each order line is text like chai 2. line turns one line into an amount, and every step that can fail returns early with an error. Two new helpers:
fmt.Sscan(s, &a, &b)("scan from a string") reads space-separated words from the stringsinto the variables you point it at (episode 18 usedfmt.Scanfor keyboard input; Sscan is the same thing on a string). It returns how many items it filled and an error.strconv.Atoi(s)(packagestrconv= string conversion;Atoi= "ASCII to integer", a name inherited from C; ASCII is the basic character encoding for English letters and digits) converts text like"42"to the int42, and returns an error for text like"two".
package main
import "fmt"
import "strconv"
var menu = map[string]float64{"chai": 10, "samosa": 15}
func line(s string) (float64, error) {
var item, qtyText string
if _, err := fmt.Sscan(s, &item, &qtyText); err != nil {
return 0, fmt.Errorf("line %q: %v", s, err)
}
qty, err := strconv.Atoi(qtyText)
if err != nil {
return 0, err
}
p, ok := menu[item]
if !ok {
return 0, fmt.Errorf("%q not on menu", item)
}
return p * float64(qty), nil
}
func main() {
var total float64
for _, s := range []string{"chai 2", "samosa two", "dosa 1", "samosa 3"} {
amt, err := line(s)
if err != nil {
fmt.Println("skip:", err)
continue
}
total += amt
}
fmt.Println("Total:", total)
}
skip: strconv.Atoi: parsing "two": invalid syntax
skip: "dosa" not on menu
Total: 65
skip: strconv.Atoi: parsing "two": invalid syntax: the standard library's own error, following the same conventions (lowercase,operation: details). We returned it unchanged withreturn 0, err.skip: "dosa" not on menu: ourfmt.Errorferror.Total: 65: two chai (20) plus three samosas (45). Every failure is reported, and the bill is right.if _, err := fmt.Sscan(...); err != nilis an if with an init statement (episode 7):errexists only inside thatif, so the nextqty, err := ...can use:=again without a clash.- The next problem: the
Atoierror doesn't say which line it came from. Adding context withfmt.Errorf("line %q: %v", s, err)fixes that, but then the error is a new*errors.errorString: if it had been the sentinelErrNotOnMenu, the caller could no longer compare it with==. Context and comparison at the same time is what wrapping solves (%w,errors.Is,errors.As,errors.Join): next episode.
Extended version: line numbers, a sentinel and a custom LineError
This version adds a third menu item with a space in its name (vada pav), parses lines with strings.Fields (split on spaces, episode 17) so multi-word items work, rejects quantities <= 0, uses the sentinel ErrNotOnMenu, and reports each bad line as a *LineError that carries the line number.
package main
import (
"errors"
"fmt"
"strconv"
"strings"
)
var menu = map[string]float64{"chai": 10, "samosa": 15, "vada pav": 20}
var ErrNotOnMenu = errors.New("item not on menu")
// LineError says which order line failed and why.
type LineError struct {
Line int
Text string
Reason string
}
func (e *LineError) Error() string {
return fmt.Sprintf("line %d %q: %s", e.Line, e.Text, e.Reason)
}
// parse turns "vada pav 2" into ("vada pav", 2).
func parse(s string) (string, int, error) {
words := strings.Fields(s)
if len(words) < 2 {
return "", 0, errors.New("need an item and a quantity")
}
last := len(words) - 1
qty, err := strconv.Atoi(words[last])
if err != nil {
return "", 0, err
}
if qty <= 0 {
return "", 0, fmt.Errorf("quantity %d must be positive", qty)
}
return strings.Join(words[:last], " "), qty, nil
}
func price(item string) (float64, error) {
p, ok := menu[item]
if !ok {
return 0, ErrNotOnMenu
}
return p, nil
}
func bill(lines []string) (float64, []error) {
var total float64
var errs []error
for i, s := range lines {
item, qty, err := parse(s)
if err != nil {
errs = append(errs, &LineError{i + 1, s, err.Error()})
continue
}
p, err := price(item)
if err == ErrNotOnMenu {
errs = append(errs, &LineError{i + 1, s, item + " is not on the menu"})
continue
}
total += p * float64(qty)
}
return total, errs
}
func main() {
lines := []string{"chai 2", "vada pav 2", "samosa two", "dosa 1", "chai", "samosa -1", "samosa 3"}
total, errs := bill(lines)
for _, err := range errs {
if le, ok := err.(*LineError); ok {
fmt.Printf("skip #%d: %s\n", le.Line, le.Reason)
}
}
fmt.Printf("%d of %d lines billed, total Rs %.2f\n", len(lines)-len(errs), len(lines), total)
if len(errs) > 0 {
fmt.Println("first problem:", errs[0])
}
}
skip #3: strconv.Atoi: parsing "two": invalid syntax
skip #4: dosa is not on the menu
skip #5: need an item and a quantity
skip #6: quantity -1 must be positive
3 of 7 lines billed, total Rs 105.00
first problem: line 3 "samosa two": strconv.Atoi: parsing "two": invalid syntax
pricereturns the sentinel, andbillcheckserr == ErrNotOnMenuto write a friendly reason. Every bad line becomes a*LineError;mainuses a type assertion to readle.Lineandle.Reason.billreturns[]error: errors are values, so a slice of them is fine. Total: 20 (chai) + 40 (vada pav) + 45 (samosa) =105.00.first problem:prints the full message fromLineError.Error(), with the line number, the text and the cause: all lowercase, joined with:.- Try it: add
"chai 0"and" "to the lines, and change"dosa 1"to"Dosa 1"(map keys are case-sensitive).
Expert corner
Inside errors.New: *errors.errorString
The real errors package is tiny. This program re-creates it, then tries the same idea with a value type instead of a pointer:
// a copy of what the errors package does
type errorString struct{ s string }
func (e *errorString) Error() string { return e.s }
func New(text string) error { return &errorString{text} }
// the same idea with a VALUE instead of a pointer
type valueError struct{ s string }
func (e valueError) Error() string { return e.s }
func main() {
a, b := New("closed"), New("closed")
fmt.Println(a == b, a == a, a, errors.New("closed"))
var c, d error = valueError{"closed"}, valueError{"closed"}
fmt.Println(c == d)
}
false true closed closed
true
a == bisfalseanda == aistrue: each call toNewallocates a new struct and returns a pointer to it. Comparing two interfaces holding pointers compares the addresses, not the text (interface equality, episode 21).- With the value type
valueError,c == distrue: two different errors with the same text are equal. That's whyerrors.Newreturns a pointer: so that every error is unique. Otherwise anyone could writeerrors.New("EOF")and accidentally equalio.EOF, and sentinels would be meaningless. - The struct is unexported (lowercase
errorString), so other packages can't build one or reach inside; they can only callError().
The standard library's errors: *fs.PathError
os.Open returns a custom error type that carries what was attempted, on which path, and the underlying reason (the folder has no menu.txt):
func main() {
_, err := os.Open("menu.txt")
fmt.Println(err)
fmt.Printf("%T\n", err)
if pe, ok := err.(*fs.PathError); ok {
fmt.Printf("Op=%q Path=%q Err=%q\n", pe.Op, pe.Path, pe.Err)
}
fmt.Println(os.Remove("menu.txt"))
}
open menu.txt: no such file or directory
*fs.PathError
Op="open" Path="menu.txt" Err="no such file or directory"
remove menu.txt: no such file or directory
open menu.txt: no such file or directory: operation, path, cause, joined with:.os.Removeuses the same type withOp="remove". Episode 34 covers files.*fs.PathErrorlives in packageio/fs; the type assertion gives you its fieldsOp,PathandErr(the cause, itself anerror). The exact cause text depends on the operating system.
*strconv.NumError and sentinels inside custom errors
func main() {
for _, s := range []string{"42", "two", "", "99999999999999999999"} {
n, err := strconv.Atoi(s)
fmt.Printf("%q -> %d, %v\n", s, n, err)
if ne, ok := err.(*strconv.NumError); ok {
fmt.Println(" Func:", ne.Func, "| Num:", ne.Num, "| syntax?", ne.Err == strconv.ErrSyntax, "| range?", ne.Err == strconv.ErrRange)
}
}
}
"42" -> 42, <nil>
"two" -> 0, strconv.Atoi: parsing "two": invalid syntax
Func: Atoi | Num: two | syntax? true | range? false
"" -> 0, strconv.Atoi: parsing "": invalid syntax
Func: Atoi | Num: | syntax? true | range? false
"99999999999999999999" -> 9223372036854775807, strconv.Atoi: parsing "99999999999999999999": value out of range
Func: Atoi | Num: 99999999999999999999 | syntax? false | range? true
strconv.Atoireturns a*strconv.NumErrorwithFunc(which function),Num(the input) andErr, a sentinel:strconv.ErrSyntax(not a number) orstrconv.ErrRange(a number, but too big for an int). Custom types and sentinels work together.- Out of range,
Atoireturns the largest int (9223372036854775807) along with the error, not0. Another reason to checkerrbefore using the value: the value is only meaningful whenerr == nil, unless the documentation says otherwise.
What fmt.Sscan returns on short input
fmt.Sscan("chai", &item, &qty) fills 1 item and returns EOF, and err == io.EOF is true (real run): the string ended before qty was read. With extra words ("chai 2 extra") it fills the two it needs, returns a nil error and ignores the rest. So in the mini project, a line chai alone produces skip: line "chai": EOF (real run, with "chai" added to the list; the total stays 65). Here io.EOF is a failure, because a quantity was expected: the same sentinel can mean "done" or "missing data" depending on who returns it. That's why the extended version uses strings.Fields and counts the words itself.
Sentinels in the standard library
io.ErrUnexpectedEOF ("unexpected EOF": the input ended in the middle of something), os.ErrNotExist ("file does not exist"), fs.ErrPermission ("permission denied"), sql.ErrNoRows ("sql: no rows in result set", from database/sql) and strconv.ErrSyntax ("invalid syntax") all print %T as *errors.errorString (real run): plain errors.New values in package-level variables. os.ErrNotExist describes the kind of failure that can sit inside a *fs.PathError; finding it through a custom error needs errors.Is (next episode), because the Err field holds an operating-system error, not the sentinel itself.
io.EOF can arrive together with data
The io.Reader rule (episode 22): Read(p []byte) (n int, err error) may return some bytes and io.EOF in the same call. testing/iotest.DataErrReader is a test helper that does exactly that:
func main() {
r := iotest.DataErrReader(strings.NewReader("chai"))
buf := make([]byte, 8)
for {
n, err := r.Read(buf)
fmt.Printf("n=%d data=%q err=%v\n", n, buf[:n], err)
if err == io.EOF {
break
}
}
}
n=4 data="chai" err=EOF
n=4 data="chai" err=EOFin one call. A loop that breaks onerr == io.EOFbefore usingbuf[:n]would lose "chai". The documented rule: process then > 0bytes first, then look at the error. This is the one big exception to "check the error before using the value".
Comparing errors can panic
== on interfaces compares (type, value). If both errors hold the same uncomparable dynamic type (a slice, a map or a function; episode 19), the comparison compiles but panics at run time:
A Problems type is a []string with an Error method, and check() returns Problems{"no milk", "no sugar"} as an error. In a real run, fmt.Println(err == io.EOF) printed false, and then fmt.Println(err == check()) crashed:
panic: runtime error: comparing uncomparable type main.Problems
goroutine 1 [running]:
main.main()
/tmp/.../main.go:18 +0x179
exit status 2
err == io.EOFwas fine: the dynamic types differ (main.Problemsvs*errors.errorString), so Go never compares the values.err == check()panicked: both aremain.Problems, a slice type. Lesson: make custom error types structs used through pointers (comparable, unique), not slices or maps.
Errors are values: a "sticky" error
Because an error is just a value, you can store it and deal with it later. A common pattern (it appears in bufio.Scanner's Err() method): a type remembers the first error, ignores every call after it, and reports it once at the end:
// Bill remembers the FIRST error; later calls do nothing.
type Bill struct {
total float64
err error
}
func (b *Bill) Add(item string, qty int) {
if b.err != nil {
return
}
p, ok := menu[item]
if !ok {
b.err = fmt.Errorf("%q not on menu", item)
return
}
b.total += p * float64(qty)
}
func (b *Bill) Total() (float64, error) { return b.total, b.err }
func main() {
var b Bill
b.Add("chai", 2)
b.Add("samosa", 1)
fmt.Println(b.Total())
var b2 Bill
b2.Add("chai", 2)
b2.Add("dosa", 1)
b2.Add("samosa", 1)
total, err := b2.Total()
fmt.Println(total, err)
}
35 <nil>
20 "dosa" not on menu
35 <nil>for a good bill. For the bad one: chai is added, dosa setsb.err, and samosa is skipped because an error is already stored. The caller writes oneif err != nilinstead of three.- This is "errors are values" in practice: instead of repeating
if err != nil, program with the error.
When not to return an error
- If something can't fail (for example
strings.ToUpper), don't add an error result just in case. - If the only failure is "not found", a
bool(comma-ok, like map lookup) is often clearer than an error:func lookup(name string) (Khata, bool). - Truly impossible situations (a bug in your own program) are for
panic(episode 26), not errors. Errors are for things that can normally go wrong: bad input, missing files, the network.
Common mistakes (and the real messages)
| You wrote | Real error / what happens | Fix |
|---|---|---|
return -1 // means not found |
no error: Total: 24, a wrong answer |
return 0, errors.New(...) |
p, err := price("dosa"), err never used |
declared and not used: err |
if err != nil { ... }, or _ on purpose |
p := price("chai") with two results |
assignment mismatch: 1 variable but price returns 2 values |
p, err := price("chai") |
return p in a (float64, error) function |
not enough return values / have (float64) / want (float64, error) |
return p, nil |
return nil, err for a float64 result |
cannot use nil as float64 value in return statement |
return the zero value: return 0, err |
err == "item not on menu" |
cannot convert "item not on menu" (untyped string constant) to type interface{Error() string} |
compare with a sentinel: err == ErrNotOnMenu |
errors.New("a") == errors.New("a") |
compiles, prints false |
one sentinel variable, created once |
return OutOfStock{...} with a pointer-receiver Error |
OutOfStock does not implement error (method Error has pointer receiver) |
return &OutOfStock{...} |
var e *OutOfStock; return e as an error |
err != nil is true with no failure |
return nil |
errors.New("Item not on menu.") |
no error: order 7: Item not on menu. reads badly |
lowercase, no punctuation |
using p before checking err |
silent wrong value (0, or max int from Atoi) |
check err first (except io.Reader's n) |
== on two errors of a slice type |
panic: runtime error: comparing uncomparable type main.Problems |
struct error types used via pointers |
Every message above is from a real run (the code for each appears earlier in these notes). The two price compile errors in full, from one file where price ended with return p (line 15) and main had p := price("chai") (line 19):
# command-line-arguments
./main.go:15:12: not enough return values
have (float64)
want (float64, error)
./main.go:19:10: assignment mismatch: 1 variable but price returns 2 values
Practice
- (Homework) Write
divide(a, b int) (int, error)that returns a sentinelErrDivByZerowhenbis 0. Inmain, divide 100 by 4 and by 0, and react to the sentinel with==. - (Homework) Write a custom error type
InsufficientFundswith fieldsNeedandHave.withdraw(balance, amount int) (int, error)returns it when the amount is too big. Starting with 500, withdraw 200 and then 450, and print how much is missing. - (Homework) Read a
strings.Readertoio.EOFwithReadByteand count the bytes. Treatio.EOFas "finished", but return any other error. Try"masala chai"and"चाय"(Hindi for chai). Why is the second number not 3? - This
validatehas a bug. What doesmainprint, and how do you fix it?
type BadName struct{ Name string }
func (e *BadName) Error() string { return "bad name " + e.Name }
func validate(name string) error {
var e *BadName
if strings.TrimSpace(name) == "" {
e = &BadName{name}
}
return e
}
func main() {
fmt.Println(validate("Asha") == nil, validate(" ") == nil)
}
- Rewrite these messages to follow Go's conventions, then predict the full line
mainprints:loadreturnserrors.New("Menu file missing!"),openreturnsfmt.Errorf("Error: opening shop: %v.", err), andmainprintsfmt.Println("startup failed:", open()).
Solution
- The sentinel is created once; the caller compares against it.
var ErrDivByZero = errors.New("division by zero")
func divide(a, b int) (int, error) {
if b == 0 {
return 0, ErrDivByZero
}
return a / b, nil
}
func main() {
for _, b := range []int{4, 0} {
q, err := divide(100, b)
if err == ErrDivByZero {
fmt.Println("100 /", b, "->", err)
continue
}
fmt.Println("100 /", b, "=", q)
}
}
100 / 4 = 25
100 / 0 -> division by zero
- The caller gets the struct back with a comma-ok type assertion and uses its data.
type InsufficientFunds struct {
Need, Have int
}
func (e *InsufficientFunds) Error() string {
return fmt.Sprintf("insufficient funds: need %d, have %d", e.Need, e.Have)
}
func withdraw(balance, amount int) (int, error) {
if amount > balance {
return balance, &InsufficientFunds{Need: amount, Have: balance}
}
return balance - amount, nil
}
func main() {
balance := 500
for _, amt := range []int{200, 450} {
nb, err := withdraw(balance, amt)
if e, ok := err.(*InsufficientFunds); ok {
fmt.Println(err)
fmt.Println("missing:", e.Need-e.Have)
continue
}
balance = nb
fmt.Println("withdrew", amt, "balance", balance)
}
}
withdrew 200 balance 300
insufficient funds: need 450, have 300
missing: 150
ReadBytereads bytes, and each Devanagari letter inचायtakes 3 bytes in UTF-8 (episode 17): 3 characters × 3 bytes = 9.
func count(s string) (int, error) {
r := strings.NewReader(s)
n := 0
for {
_, err := r.ReadByte()
if err == io.EOF {
return n, nil // finished: not a failure
}
if err != nil {
return n, err // a real failure
}
n++
}
}
func main() {
fmt.Println(count("masala chai"))
fmt.Println(count("चाय"))
}
11 <nil>
9 <nil>
- The buggy version prints
false false(real run):validate("Asha")returns a typed nil, a nil*BadNameinside a non-nilerror. Fix: return the pointer only on failure, and a literalnilotherwise.
func validate(name string) error {
if strings.TrimSpace(name) == "" {
return &BadName{name}
}
return nil
}
func main() {
fmt.Println(validate("Asha") == nil, validate(" ") == nil)
}
true false
- The original prints
startup failed: Error: opening shop: Menu file missing!.(real run): a second "Error", a capital in the middle, and!.at the end. Lowercase, no punctuation, no "Error:" prefix (the caller already knows it's an error):
func load() error { return errors.New("menu file missing") }
func open() error {
if err := load(); err != nil {
return fmt.Errorf("opening shop: %v", err)
}
return nil
}
func main() {
fmt.Println("startup failed:", open())
}
startup failed: opening shop: menu file missing
Quick quiz
1. What does this print? (From the video.)
package main
import (
"errors"
"fmt"
)
var ErrEmpty = errors.New("empty")
func first(s []int) (int, error) {
if len(s) == 0 {
return 0, ErrEmpty
}
return s[0], nil
}
func main() {
_, err := first(nil)
fmt.Println(err == ErrEmpty, err == errors.New("empty"))
}
A. true true · B. true false · C. false false · D. compile error
Answer
B. first(nil) returns the sentinel ErrEmpty itself, so err == ErrEmpty is true. errors.New("empty") creates a new, different value, so the second comparison is false. Real output: true false.
2. check declares var e *OutOfStock, never sets it, and returns e as an error. What is err == nil in the caller?
Answer
false. The interface holds the type *OutOfStock with a nil pointer inside: a typed nil. The video's run printed failed? *main.OutOfStock false. Return a literal nil instead.
3. Does this compile? p, err := price("dosa") followed only by fmt.Println(p).
Answer
No: declared and not used: err. Check it with if err != nil, or discard it on purpose with p, _ := price("dosa").
4. A loop reads bytes with ReadByte and stops on io.EOF. Is io.EOF a failure?
Answer
No. It's a sentinel error that means "nothing left to read": the normal way a reader says it's finished. Any other error would be a real failure. (It can mean failure when data was expected, like fmt.Sscan running out of words.)
5. Which message follows Go's conventions? A. "Item not on menu." · B. "item not on menu" · C. "Error: item not on menu!" · D. "ITEM NOT ON MENU\n"
Answer
B. Lowercase start, no ending punctuation, no newline, no "Error:" prefix. Messages get joined (billing failed: order 7: item not on menu), so anything else reads badly in the middle of a line.
Interview questions
1. How does Go handle errors, and why doesn't it use exceptions?
A function that can fail returns an error as its last result; the caller checks if err != nil right after the call and handles or returns it. Errors are ordinary values, so control flow is explicit: every place that can fail is visible, and nothing jumps up the stack unseen. The cost is verbosity. Go does have panic and recover, but they are for truly exceptional situations such as bugs, not for expected failures like bad input or a missing file.
2. What is the error type?
A predeclared interface with one method: Error() string. Any type with that method is an error. Its zero value is nil, meaning "no error". fmt prints an error by calling Error().
3. What is a sentinel error? What are its pros and cons?
A single error value stored in an exported package-level variable, conventionally named ErrX (io.EOF, sql.ErrNoRows), that callers compare with == to detect a specific condition. Pros: simple and cheap. Cons: it carries no extra data, it becomes part of your package's public API forever, and adding context with fmt.Errorf("...: %v", err) breaks the == comparison (solved by wrapping with %w and errors.Is).
4. Why does errors.New("a") == errors.New("a") give false?
errors.New returns a pointer to a new errorString struct each time, and comparing interfaces that hold pointers compares the addresses. This is deliberate: every error is unique, so nobody can accidentally create a value equal to a sentinel like io.EOF.
5. When would you write a custom error type?
When callers need structured data about the failure, not just a message: which line, which file, how much was missing (*fs.PathError has Op, Path, Err). The caller gets it back with a type assertion (or errors.As, next episode). Use a struct with a pointer-receiver Error() method and name it XxxError.
6. Explain the nil error trap.
An interface is nil only when both its dynamic type and value are nil. Returning a nil *MyError variable as an error stores the type *MyError, so err != nil is true even though nothing failed. Always return nil explicitly on success, and give helper functions the result type error, not *MyError.
7. What are Go's conventions for error messages?
Start lowercase (unless a proper noun or acronym), no ending punctuation, no newlines, because messages are joined with : as they travel up (open menu.txt: no such file or directory). Say what failed and on which input. staticcheck reports violations as ST1005.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Exception | in other languages, a mechanism that jumps out of a function to a catch block; Go has none |
Java throw, Python raise |
| Magic value | a normal-looking return value that secretly means "it failed" | return -1 // not found |
| In-band signal | a failure signal sent in the same channel as the real data, so it can be mistaken for data | -1 added to the total |
nil |
"nothing here": the zero value of pointers, slices, maps, interfaces; for errors, "no error" | return p, nil |
| Zero value | the value a variable has before assignment; returned beside an error | 0, "", nil |
error interface |
the predeclared interface interface{ Error() string } |
var err error |
Error() method |
returns the error's message; fmt calls it to print an error | err.Error() |
errors.New |
makes a new, unique error with a fixed message | errors.New("item not on menu") |
fmt.Errorf |
like fmt.Sprintf, but returns an error |
fmt.Errorf("%q not on menu", item) |
| Error as last result | the convention that a function's error comes after its other results | func price(item string) (float64, error) |
if err != nil |
the check after every call that can fail | if err != nil { return 0, err } |
| Happy path | the code that runs when nothing goes wrong | kept at the left margin |
| Early return | leaving a function as soon as a check fails, instead of nesting else |
if qty <= 0 { return 0, err } |
| Errors are values | errors are ordinary values: stored, passed, compared, collected | []error, err == ErrClosed |
| Package-level variable | a variable declared outside any function, visible in the whole package | var ErrClosed = errors.New(...) |
| Sentinel error | one fixed error value in a variable, compared with ==; named ErrX |
ErrNotOnMenu, io.EOF |
EOF / io.EOF |
"end of file": the sentinel meaning there's nothing left to read | if err == io.EOF { break } |
strings.Reader |
a reader over a string, made by strings.NewReader |
r.ReadByte() |
| Custom error type | your own type with an Error() string method, carrying data |
*OutOfStock{Item, Left} |
| Type assertion | getting the concrete value out of an interface (episode 22) | e, ok := err.(*OutOfStock) |
| Comma-ok | a second bool result saying whether something worked |
p, ok := menu[item] |
| Typed nil | a nil pointer inside a non-nil interface; != nil is true |
var e *OutOfStock; return e |
| Dynamic type | the concrete type stored in an interface right now (episode 21) | %T → *errors.errorString |
*errors.errorString |
the unexported struct type behind errors.New and plain fmt.Errorf |
%T of errors.New("x") |
Blank identifier _ |
a name that discards a value: ignoring an error on purpose | p, _ := price("dosa") |
declared and not used |
the compile error for an unused local variable, which catches forgotten errors | declared and not used: err |
| Message conventions | lowercase start, no ending punctuation, no newlines | "item not on menu" |
| Context (in an error) | extra detail about where the error happened, added as a prefix | order 7: item not on menu |
fmt.Sscan |
reads space-separated words from a string into variables | fmt.Sscan("chai 2", &item, &qty) |
strconv.Atoi |
"ASCII to integer": converts text to an int, with an error | strconv.Atoi("two") → invalid syntax |
*strconv.NumError |
Atoi's error type: Func, Num, Err (ErrSyntax / ErrRange) |
parsing "two": invalid syntax |
*fs.PathError |
os's error type: Op, Path, Err |
open menu.txt: no such file or directory |
| Sticky error | a type that stores the first error and ignores later work | Bill.Add with b.err |
| ST1005 | the staticcheck check for badly formatted error strings | capitalised or ending in . |
| Wrapping | adding context while keeping the original error findable (episode 25) | %w, errors.Is, errors.As |
| Panic | a run-time crash for bugs, not for expected failures (episode 26) | comparing uncomparable type |
Summary
- Magic values (
0,-1) are in-band signals: they look like data, so failures hide in the result (Total: 24). Use a second result of typeerror, always last, with the zero value beside it on failure andnilon success. - Make errors with
errors.New(a fixed message) orfmt.Errorf(a formatted message). Check withif err != nil, return early, keep the happy path at the left margin. An unusederris a compile error;_ignores one on purpose. erroris a built-in interface,Error() string; nil means no error, andfmtprints the message by callingError().- Errors are values. A sentinel error (
var ErrNotOnMenu = errors.New(...)) is created once and compared with==; eacherrors.Newis unique (false), because it returns a pointer.io.EOFmeans "finished", not "failed". - Custom error types carry data (
OutOfStock{Item, Left},*fs.PathError,*strconv.NumError); get it back with a comma-ok type assertion. Use a pointer receiver and return&T{...}. - Never return a typed nil (a nil
*MyErroras anerror): it is not== nil.return nilon success. - Messages: lowercase, no ending punctuation, no newlines, because they are joined:
billing failed: order 7: item not on menu.
Next episode: Error wrapping and handling strategy: keep the original error inside a message with %w, find it again with errors.Is and errors.As, combine several with errors.Join, and decide when to handle an error and when to return it.