Every write in this course returns an error, and every function passes it up. That code is easy to get wrong in a way no ordinary run will show: a strings.Builder and the terminal never fail, so a function that forgets to return a write error still produces perfect output. The failure only appears in production, as a report that silently stops halfway when a disk fills up. To prove the error handling works, a check needs a destination that fails on purpose.
Any type with a Write(p []byte) (int, error) method satisfies io.Writer, so you can write one in three lines that returns an error on every call. No files or network are involved.
Predict and run
Which error is visible to the caller?
package main
import (
"errors"
"fmt"
"io"
)
var errClosed = errors.New("destination closed")
type brokenWriter struct{}
func (brokenWriter) Write(p []byte) (int, error) { return 0, errClosed }
func report(w io.Writer) error {
_, err := fmt.Fprintln(w, "Task queue")
return err
}
func main() {
err := report(brokenWriter{})
fmt.Println(errors.Is(err, errClosed))
}Check your prediction
truefmt.Fprintln calls the writer's Write and hands back whatever error it returned, so report passes errClosed straight to its caller. func (brokenWriter) Write has no receiver name because the method never uses it.
Find the bug
This report writes a heading and a line per task. The check uses a broken writer and expects an error back, but report claims everything went fine. Find the problem before you open the hint.
package main
import (
"errors"
"fmt"
"io"
)
var errClosed = errors.New("destination closed")
type brokenWriter struct{}
func (brokenWriter) Write(p []byte) (int, error) { return 0, errClosed }
func report(w io.Writer, titles []string) error {
fmt.Fprintln(w, "Task queue")
for _, title := range titles {
fmt.Fprintln(w, "-", title)
}
return nil
}
func main() {
err := report(brokenWriter{}, []string{"Read", "Draft"})
fmt.Println("report returned:", err)
}report returned: <nil>Check your fix
Every Fprintln result is thrown away and the function always returns nil. Check each write and return the first error:
package main
import (
"errors"
"fmt"
"io"
)
var errClosed = errors.New("destination closed")
type brokenWriter struct{}
func (brokenWriter) Write(p []byte) (int, error) { return 0, errClosed }
func report(w io.Writer, titles []string) error {
if _, err := fmt.Fprintln(w, "Task queue"); err != nil {
return err
}
for _, title := range titles {
if _, err := fmt.Fprintln(w, "-", title); err != nil {
return err
}
}
return nil
}
func main() {
err := report(brokenWriter{}, []string{"Read", "Draft"})
fmt.Println("report returned:", err)
}report returned: destination closedGo doesn't complain about an ignored Fprintln result, and with a builder or the terminal the buggy version's output is identical. Only a writer that fails exposes the difference, which is the whole reason to build one.
Practice
Your turn
A writer that fails on every call can't tell whether a function stops at the first failure or keeps going. Write limitWriter, which accepts a set number of writes and then fails with errFull. It counts two things: the writes it accepted, and every call to Write, accepted or not. Use it to check the starter's writeList: allow 2 writes, then print the error writeList returned, whether it is errFull, how many writes were accepted and how many were attempted. The output should be:
destination full
true
accepted: 2
attempts: 3package main
import (
"errors"
"fmt"
"io"
)
var errFull = errors.New("destination full")
func writeList(w io.Writer, titles []string) error {
for _, title := range titles {
if _, err := fmt.Fprintln(w, title); err != nil {
return err
}
}
return nil
}
func main() {
titles := []string{"Read", "Draft", "Review", "Send"}
fmt.Println(len(titles), errFull)
}Hint 1: the idea
The writer has state that changes on every call: how many writes it still allows, and the two counts. Only the count of attempts can tell a function that stops apart from one that keeps going, because once the limit is reached, both get the same number of accepted writes. Changing state means a pointer receiver, so it is &w that satisfies io.Writer, exactly as with strings.Builder.
Hint 2: a first step
Declare the struct with the counters it needs, and start with a Write method on *limitWriter that always succeeds, returning len(p), nil and counting every call. Run it: writeList returns <nil> and attempts: 4. Then add the limit.
Worked solution
package main
import (
"errors"
"fmt"
"io"
)
var errFull = errors.New("destination full")
type limitWriter struct {
left int
accepted int
attempts int
}
func (w *limitWriter) Write(p []byte) (int, error) {
w.attempts++
if w.left == 0 {
return 0, errFull
}
w.left--
w.accepted++
return len(p), nil
}
func writeList(w io.Writer, titles []string) error {
for _, title := range titles {
if _, err := fmt.Fprintln(w, title); err != nil {
return err
}
}
return nil
}
func main() {
titles := []string{"Read", "Draft", "Review", "Send"}
w := limitWriter{left: 2}
err := writeList(&w, titles)
fmt.Println(err)
fmt.Println(errors.Is(err, errFull))
fmt.Println("accepted:", w.accepted)
fmt.Println("attempts:", w.attempts)
}destination full
true
accepted: 2
attempts: 3attempts: 3 is the line that proves writeList stopped at the third title: two accepted writes, then one that failed. accepted: 2 alone proves nothing about stopping. A version that remembered the error and kept looping would also get exactly 2 accepted writes, because the limit is used up, but it would print attempts: 4. Counting attempts is what gives this writer an advantage over one that always fails. A successful Write returns len(p): the io.Writer rules say a count shorter than len(p) must come with an error, and callers rely on that.
Completion is saved in this browser only. It does not measure mastery.