CodeBlanks Logo Icon CodeBlanks

fmt.Errorf

Learn to create formatted errors with Errorf.

fmt.Errorf

fmt.Errorf creates a formatted error. The %w verb wraps the underlying error: context is added to the message but the original error isn't lost.

f, err := os.Open(yol)
if err != nil {
    return fmt.Errorf("ayar okunamadı (%s): %w", yol, err)
}

The caller can still query the root cause with errors.Is(err, fs.ErrNotExist). With %v only the text would be copied and the chain would break.

errors.As and custom errors

To decide by error type, errors.As searches the chain for a specific type:

type DogrulamaHatasi struct{ Alan string }
func (e *DogrulamaHatasi) Error() string { return e.Alan + " geçersiz" }

err := fmt.Errorf("kayıt: %w", &DogrulamaHatasi{"eposta"})
var dh *DogrulamaHatasi
if errors.As(err, &dh) {
    fmt.Println(dh.Alan)  // eposta
}

Since Go 1.20 several %w verbs can be used in one Errorf.

Practice Wrapped error

Declare var ErrYok = errors.New("kayıt yok"). The function bul(id int) error returns fmt.Errorf("bul %d: %w", id, ErrYok). Print the error and errors.Is(err, ErrYok) on separate lines.

Starter code

main.go
package main

import (
    "errors"
    "fmt"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "errors"
    "fmt"
)

var ErrYok = errors.New("kayıt yok")

func bul(id int) error {
    return fmt.Errorf("bul %d: %w", id, ErrYok)
}

func main() {
    err := bul(7)
    fmt.Println(err)
    fmt.Println(errors.Is(err, ErrYok))
}

Expected output

bul 7: kayıt yok
true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 With an error wrapped using <code>%v</code> instead of <code>%w</code>, what does <code>errors.Is</code> return?

  • false; the chain is broken Correct answer
  • true
  • panic
  • nil

Explanation: %v only turns the message into text; without an Unwrap method errors.Is can't reach the original error.

2 Wrap the error

Question
return fmt.Errorf("bağlantı kurulamadı: ____", err)
Answer
return fmt.Errorf("bağlantı kurulamadı: %w", err)

Explanation: %w wraps the error; errors.Is and errors.As can reach it in the chain.

3 Function and role

Term Meaning
fmt.Errorf + %w Wrap with context
errors.Is Is it a specific error?
errors.As Is it a specific type?
errors.Unwrap Unwrap one level

All lessons in Intermediate