Go course

Errorsfmt.Errorf and Wrapping Errors

Go

Display

Theme

Errors · Test exercise

fmt.Errorf and Wrapping Errors

More informative error messages

errors.New only accepts fixed text. To slip data into the message, use fmt.Errorf, which works like fmt.Sprintf but produces an error:

return fmt.Errorf("kursi %d sudah dipesan", nomor)

Sentinel errors

Sometimes the caller needs to know the kind of failure, not just read its message. The way to do that: create a package-level error that can be compared. An error like this is called a sentinel error, and its name usually starts with Err:

var ErrTidakDitemukan = errors.New("data tidak ditemukan")

Wrapping with %w

We often want to add context and still keep the original error. The special %w verb in fmt.Errorf wraps the error:

func cariMember(id int) error {
	return fmt.Errorf("cari member %d: %w", id, ErrTidakDitemukan)
}

The message becomes cari member 7: data tidak ditemukan ("find member 7: data not found"), but the original error is still stored inside.

errors.Is

Because the error has been wrapped, the comparison err == ErrTidakDitemukan evaluates to false. Use errors.Is instead, which walks the whole wrapping chain:

err := cariMember(7)
if errors.Is(err, ErrTidakDitemukan) {
	fmt.Println("member belum terdaftar")
}

%v only copies the error's text; %w copies the text and keeps the original error so it can be checked with errors.Is.

Task

An online store validates orders before processing them. Two sentinel errors are already provided:

var ErrJumlahTidakValid = errors.New("jumlah tidak valid")
var ErrStokHabis = errors.New("stok habis")

Complete func pesan(nama string, stok, jumlah int) error. Check in order:

  1. jumlah <= 0 → an fmt.Errorf that wraps ErrJumlahTidakValid, with the final message pesan <nama>: jumlah tidak valid ("order <name>: invalid quantity").
  2. stok == 0 → wrap ErrStokHabis, final message pesan <nama>: stok habis ("order <name>: out of stock").
  3. jumlah > stok → a plain error (wrapping nothing) with the message pesan <nama>: hanya tersedia <stok> ("order <name>: only <stock> available").
  4. Otherwise → nil.

Example: pesan("Kaos Polos", 0, 2) produces an error with the message pesan Kaos Polos: stok habis, and errors.Is(err, ErrStokHabis) is true.

main.go
package main

import (
	"errors"
	"fmt"
)

var ErrJumlahTidakValid = errors.New("jumlah tidak valid")
var ErrStokHabis = errors.New("stok habis")

func pesan(nama string, stok, jumlah int) error {
	// TODO: gunakan fmt.Errorf dengan %w untuk membungkus sentinel error
	return nil
}

func main() {
	err := pesan("Kaos Polos", 0, 2)
	fmt.Println("Error:", err)
	fmt.Println("Stok habis?", errors.Is(err, ErrStokHabis))
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)