errors

package
v0.0.57-rc.4 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2023 License: MIT Imports: 5 Imported by: 1

Documentation

Overview

Package errors implements functions to manipulate errors.

Example (StackTraceFormatting)
package main

import (
	"fmt"

	"github.com/komuw/ong/errors"
)

const expectedUser = "admin"

func login(user string) error {
	if user == expectedUser {
		return nil
	}

	return errors.New("invalid user")
}

func main() {
	err := login("badGuy")
	fmt.Printf("%+v", err)
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Dwrap added in v0.0.29

func Dwrap(errp *error)

Dwrap adds stack traces to the error. It does nothing when *errp == nil.

Example
package main

import (
	"fmt"

	"github.com/komuw/ong/errors"

	"golang.org/x/exp/slices"
)

func main() {
	fetchUser := func(u string) (errp error) {
		defer errors.Dwrap(&errp)

		users := []string{"John", "Alice", "Kamau"}
		if !slices.Contains(users, u) {
			return fmt.Errorf("user %s not found", u)
		}

		return nil
	}

	e := fetchUser("Emmy")
	fmt.Printf("%+#v", e)
}
Output:

func New

func New(text string) error

New returns an error with the supplied message. It also records the stack trace at the point it was called.

Error values implement fmt.Formatter and can be formatted by the fmt package. The following verbs are supported:

%s   print the error.
%v   see %s
%+v  print the error and stacktrace.

func StackTrace

func StackTrace(err error) string

StackTrace returns the stack trace contained in err, if any, else an empty string.

func Wrap

func Wrap(err error) error

Wrap returns err, capturing a stack trace. It is a no-op if err had already been wrapped by this library.

Example
package main

import (
	"fmt"
	"os"

	"github.com/komuw/ong/errors"
)

func main() {
	opener := func(p string) error {
		_, err := os.Open(p)
		if err != nil {
			return errors.Wrap(err)
		}
		return nil
	}

	fmt.Printf("%+v", opener("/this/file/does/not/exist.txt"))
}
Output:

Types

This section is empty.

Jump to

Keyboard shortcuts

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