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.
In more detail
Each layer adds the operation it was doing, giving messages like read config: missing. The wrapped errors form a chain that errors.Is and errors.As search. Wrapping makes the inner error part of your function's promise to callers, so wrap deliberately.
Example
return fmt.Errorf("read config: %w", ErrMissing)Related terms
- 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.
- errors.Is — The function that reports whether an error, or any error wrapped inside it, is a particular target error.
- sentinel error — A specific error value published in a package-level variable, such as io.EOF or os.ErrNotExist, that callers can test for with errors.Is.
- error — In Go, an ordinary value of the built-in error type that a function returns to report that something went wrong.
Taught in
- Wrapping Errors and errors.Is — Concurrent Systems Programming with Go
- Context Cancellation and Timeouts — Concurrent Systems Programming with Go
- Files and the os Package — Concurrent Systems Programming with Go
- Streams and the io Package — Concurrent Systems Programming with Go
- Calling APIs with net/http Client — Concurrent Systems Programming with Go
- Handling Timeouts and Errors — Concurrent Systems Programming with Go