fmt.Errorf
The fmt function that creates an error with a formatted message, and wraps another error inside it when you use the %w verb.
In more detail
fmt.Errorf("host %s is unknown", host) adds useful detail to a message. fmt.Errorf("read config: %w", err) also keeps the original error inside, so errors.Is can still find it. Use %v instead of %w when callers should not depend on the cause.
Example
fmt.Errorf("start worker: %w", ErrBusy)Related terms
- error wrapping — Adding context to an error while keeping the original error inside it, so the message explains what failed and code can still test the cause.
- errors.Is — The function that reports whether an error, or any error wrapped inside it, is a particular target error.
- format verb — A placeholder starting with % in a format string, such as %s or %d, that says how to print the matching argument.
- error — In Go, an ordinary value of the built-in error type that a function returns to report that something went wrong.
Taught in
- Errors as Values — Concurrent Systems Programming with Go
- Wrapping Errors and errors.Is — Concurrent Systems Programming with Go
- Panics and Recover — Concurrent Systems Programming with Go
- Writing Table Driven Tests — Concurrent Systems Programming with Go
- Handling Timeouts and Errors — Concurrent Systems Programming with Go