Custom Error Types
Since error is just an interface, you can create your own error types that carry extra data. All it takes is a struct with an Error() string method:
type ErrSaldo struct {
Butuh int
Tersedia int
}
func (e ErrSaldo) Error() string {
return fmt.Sprintf("saldo kurang: butuh %d, tersedia %d", e.Butuh, e.Tersedia)
}
func bayar(saldo, harga int) error {
if harga > saldo {
return ErrSaldo{Butuh: harga, Tersedia: saldo}
}
return nil
}
An ErrSaldo value can be returned as an error, wrapped with %w, and printed like any other error. Its message comes from the Error() method:
err := fmt.Errorf("checkout: %w", bayar(5000, 12000))
fmt.Println(err) // checkout: saldo kurang: butuh 12000, tersedia 5000
Custom type or sentinel error?
The two are often used together:
- A sentinel error (
var ErrX = errors.New(...)) fits failures where the kind alone is enough, such as "data not found". The caller checks it witherrors.Is. - A custom error type fits when the failure needs to carry data, such as which field is wrong or how much balance is missing. That data shows up in the error message too.
errors.As
Sometimes the caller wants to read the fields inside a custom error, not just its message. For that, Go provides errors.As, which walks the wrapping chain looking for an error of a particular type:
var es ErrSaldo
if errors.As(err, &es) {
fmt.Println("kurang", es.Butuh-es.Tersedia) // kurang 7000
}
Notice &es: we pass the variable's address so that errors.As can fill it in (the & sign is covered fully in the Pointers chapter). If a match is found, errors.As returns true and es has been filled.
Note: the
errors.Asexample above is for reading only. The Go runtime in Nibble can't runerrors.Ason custom error types yet (a runtime limitation), so the exercises in this chapter don't use it. With Go installed on your own machine, the code above runs just fine.
In short:
errors.Is(err, target): is there an error in the chain that is the same astarget? A good fit for sentinel errors.errors.As(err, &target): is there an error in the chain of the same type astarget? If so, copy it intotarget. A good fit for custom error types.
Task
A chat app validates messages before sending them. A custom error type and one sentinel error are already declared:
type ErrValidasi struct {
Field string
Alasan string
}
var ErrPesanKosong = errors.New("pesan kosong")
Complete:
func (e ErrValidasi) Error() string: return<Field>: <Alasan>, for examplepengirim: tidak boleh kosong("sender: must not be empty").func validasiPesan(pengirim, isi string) error: check in order:pengirim == ""→ErrValidasi{Field: "pengirim", Alasan: "tidak boleh kosong"}isi == ""→ErrPesanKosonglen(isi) > 40→ErrValidasi{Field: "isi", Alasan: "maksimal 40 karakter"}("at most 40 characters")- otherwise →
nil
The kirimPesan function, which wraps the error from validasiPesan with %w, is already provided. Don't change it. The hidden tests check the error messages from kirimPesan, such as kirim pesan gagal: isi: maksimal 40 karakter, and use errors.Is for ErrPesanKosong.
len(s)returns the length of a string in bytes. For plain ASCII text, one letter = one byte.