Go Reference ยท fmt Package
Go fmt.Errorf() function
Reference for Go fmt.Errorf(): build error values from format strings, wrap errors with %w, wrap several at once, and inspect them with errors.Is and As.
fmt.Errorf creates an error whose message is produced by formatting, just like Sprintf. Its special feature is the %w verb: when the format contains %w with an error argument, the new error wraps that error, and errors.Is, errors.As and errors.Unwrap can still find the original cause.
Wrapping lets each layer add context ("load config: open file: permission denied") without hiding the underlying error that callers may want to test.
return fmt.Errorf("load config %q: %w", path, err)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func Errorf(format string, a ...any) error
| Name | Description |
|---|---|
format |
Format string; may contain %w. |
a |
Operands. Each %w operand must be a non-nil value implementing error. |
Returns an error.
- With no
%w, the result is a plain error anderrors.Unwrapreturnsnil. - With exactly one
%w, the error has anUnwrap() errormethod returning the operand. - With several
%w(Go 1.20+), the error hasUnwrap() []error, anderrors.Isanderrors.Ascheck all of them.
Edge cases
- A
%woperand that is not an error produces%!w(string=...)text, andgo vetreports it. - A
niloperand with%wprints%!w(<nil>). %wis only valid inErrorf. Other print functions format it as a bad verb.
Usage notes
- Wrap when callers may need to inspect the cause; use
%vwhen the cause is an implementation detail you do not want to make part of your API. - Message convention: lowercase, no trailing punctuation, no repetition of the wrapped message, e.g.
"open config: %w". - Prefer
%wat the end of the message so the chain reads from outside in:a: b: c. - For a plain constant message with no formatting,
errors.Newis simpler. Since Go 1.24go vetalso warns about non-constant format strings with no arguments: writefmt.Errorf("%s", msg). - Use
errors.Jointo combine independent errors without a message; useErrorfwith several%wwhen you also need a message. - Wrapping adds one allocation per layer; it is cheap compared to the clarity it buys. Do not wrap on the hot path of expected failures such as
io.EOFchecks. - Sentinel errors such as
ErrNotFoundshould be compared witherrors.Is, never with==after wrapping.