Documentation
¶
Overview ¶
Package errorfmt provides a helper function to decorate errors with additional context.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Handlef ¶
func Handlef(format string, a ...interface{})
Handlef decorates an error with additional context.
func Frob(name string) (err error) {
defer errorfmt.Handlef("frob widget %s: %w", name, &err)
...
}
Its behavior is almost the same as fmt.Errorf, with a few differences:
- There must be exactly one *error argument.
- Instead of returning a value, Handlef assigns its result via this pointer, to update the error in place.
- The *error is dereferenced before formatting. (Therefore, verb %w also accepts *error.)
- If it points to a nil error, Handlef does nothing.
These differences make it more convenient to use Handlef in a defer statement at the top of a block.
Example ¶
package main
import (
"errors"
"fmt"
"kr.dev/errorfmt"
)
func main() {
err := Frob("baz")
if err != nil {
fmt.Println(err)
}
}
func Frob(name string) (err error) {
defer errorfmt.Handlef("frob widget %s: %w", name, &err)
err = step1()
if err != nil {
return err
}
err = step2()
if err != nil {
return err
}
return nil
}
func step1() error { return nil }
func step2() error { return errors.New("step2 failed") }
Output: frob widget baz: step2 failed
Types ¶
This section is empty.
Click to show internal directories.
Click to hide internal directories.