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")
}
%vonly copies the error's text;%wcopies the text and keeps the original error so it can be checked witherrors.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:
jumlah <= 0→ anfmt.Errorfthat wrapsErrJumlahTidakValid, with the final messagepesan <nama>: jumlah tidak valid("order <name>: invalid quantity").stok == 0→ wrapErrStokHabis, final messagepesan <nama>: stok habis("order <name>: out of stock").jumlah > stok→ a plain error (wrapping nothing) with the messagepesan <nama>: hanya tersedia <stok>("order <name>: only <stock> available").- 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.