Go 1.27 reference · Formatting, Strings and Text
Go fmt.Errorf Function
Create an error with a formatted message; the %w verb wraps another error so errors.Is and errors.As can find it.
Go 1.27
Syntax
func Errorf(format string, a ...any) error
Parameters
| Parameter | Description |
|---|---|
format |
A format string; %w wraps an error (several %w are allowed). |
Examples
package main
import (
"errors"
"fmt"
"os"
)
func main() {
base := os.ErrNotExist
err := fmt.Errorf("load config %q: %w", "app.toml", base)
fmt.Println(err)
fmt.Println(errors.Is(err, os.ErrNotExist))
}
Output
load config "app.toml": file does not exist true
Run this on your computer — see “Get Started” for setup.
package main
import (
"errors"
"fmt"
)
func main() {
inner := errors.New("connection refused")
lost := fmt.Errorf("query failed: %v", inner) // %v: the chain is lost
kept := fmt.Errorf("query failed: %w", inner)
fmt.Println(errors.Is(lost, inner), errors.Is(kept, inner))
}
Output
false true
Run this on your computer — see “Get Started” for setup.
Related
errors.Is and errors.As· Check whether an error chain contains a specific error value (Is) or an error of a specific type (As).fmt.Printf· Print formatted output using verbs like %v, %+v, %d, %s, %q, %.2f and %T, with width and alignment options.- Go Error Handling · tutorial