errorfmt

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 17, 2022 License: MIT Imports: 1 Imported by: 2

README

Package errorfmt annotates Go error values.

https://kr.dev/errorfmt

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. Its behavior is almost the same as fmt.Errorf, with a few differences:

  1. There must be exactly one *error argument.
  2. Instead of returning a value, Handlef assigns its result via this pointer, to update the error in place.
  3. The *error is dereferenced before formatting. (Therefore, verb %w also accepts *error.)
  4. 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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL