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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

func Errorf(format string, a ...any) error

Parameters

ParameterDescription
format A format string; %w wraps an error (several %w are allowed).

Examples

Example 1
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.

%w versus %v
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.

Was this page helpful?