errors

package module
v3.3.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Jul 4, 2018 License: MIT Imports: 6 Imported by: 0

README

Package errors

Project status Build Status Go Report Card GoDoc License

Package errors is an errors wrapping package to help propagate and chain errors as well as attach stack traces, tags(additional information) and even a Type classification system to categorize errors into types eg. Permanent vs Transient.

Common Questions

Why another package? Because IMO most of the existing packages either don't take the error handling far enough, too far or down right unfriendly to use/consume.

Features

  • works with go-playground/log, the Tags will be added as Field Key Values and Types will be concatenated as well when using WithError
  • helpers to extract and classify error types using RegisterHelper(...), many already existing such as ioerrors, neterrors, awserrors...

Installation

Use go get.

go get -u github.com/go-playground/errors

Usage

package main

import (
	"fmt"
	"io"

	"github.com/go-playground/errors"
)

func main() {
	err := level1("testing error")
	fmt.Println(err)
	if errors.HasType(err, "Permanent") {
		// os.Exit(1)
	}

	// root error
	cause := errors.Cause(err)
	fmt.Println(cause)

	// can even still inspect the internal error
	fmt.Println(errors.Cause(err) == io.EOF) // will extract the cause for you
	fmt.Println(errors.Cause(cause) == io.EOF)
}

func level1(value string) error {
	if err := level2(value); err != nil {
		return errors.Wrap(err, "level2 call failed")
	}
	return nil
}

func level2(value string) error {
	err := fmt.Errorf("this is an %s", "error")
	return errors.Wrap(err, "failed to do something").AddTypes("Permanent").AddTags(errors.T("value", value))
}

or using stack only

package main

import (
	"fmt"

	"strings"

	"github.com/go-playground/errors"
)

func main() {
	// maybe you just want to grab a stack trace and process on your own like go-playground/log
	// uses it to produce a stack trace log message
	frame := errors.Stack()
	name := fmt.Sprintf("%n", frame)
	file := fmt.Sprintf("%+s", frame)
	line := fmt.Sprintf("%d", frame)
	parts := strings.Split(file, "\n\t")
	if len(parts) > 1 {
		file = parts[1]
	}

	fmt.Printf("Name: %s File: %s Line: %s\n", name, file, line)
}

Package Versioning

I'm jumping on the vendoring bandwagon, you should vendor this package as I will not be creating different version with gopkg.in like allot of my other libraries.

Why? because my time is spread pretty thin maintaining all of the libraries I have + LIFE, it is so freeing not to worry about it and will help me keep pouring out bigger and better things for you the community.

License

Distributed under MIT License, please see license file in code for more details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Cause

func Cause(err error) error

Cause extracts and returns the root wrapped error (the naked error with no additional information

func HasType

func HasType(err error, typ string) bool

HasType is a helper function that will recurse up from the root error and check that the provided type is present using an equality check

func LookupTag

func LookupTag(err error, key string) interface{}

LookupTag recursively searches for the provided tag and returns it's value or nil

func RegisterHelper added in v1.2.0

func RegisterHelper(helper Helper)

RegisterHelper adds a new helper function to extract Type and Tag information. errors will run all registered helpers until a match is found. NOTE helpers are run in the order they are added.

Types

type Chain

type Chain []*Link

Chain contains the chained errors, the links, of the chains if you will

func New added in v1.3.0

func New(s string) Chain

New creates an error with the provided text and automatically wraps it with line information.

func Newf

func Newf(format string, a ...interface{}) Chain

Newf creates an error with the provided text and automatically wraps it with line information. it also accepts a varadic for optional message formatting.

func Wrap

func Wrap(err error, prefix string) Chain

Wrap encapsulates the error, stores a contextual prefix and automatically obtains a stack trace.

func WrapSkipFrames

func WrapSkipFrames(err error, prefix string, n uint) Chain

WrapSkipFrames is a special version of Wrap that skips extra n frames when determining error location. Normally only used when wrapping the library

func Wrapf

func Wrapf(err error, prefix string, a ...interface{}) Chain

Wrapf encapsulates the error, stores a contextual prefix and automatically obtains a stack trace. it also accepts a varadic for prefix formatting.

func (Chain) AddTag

func (c Chain) AddTag(key string, value interface{}) Chain

AddTag allows the addition of a single tag

func (Chain) AddTags

func (c Chain) AddTags(tags ...Tag) Chain

AddTags allows the addition of multiple tags

func (Chain) AddTypes

func (c Chain) AddTypes(typ ...string) Chain

AddTypes sets one or more categorized types on the Link error

func (Chain) Error

func (c Chain) Error() string

Error returns the formatted error string

func (Chain) Wrap

func (c Chain) Wrap(prefix string) Chain

Wrap adds another contextual prefix to the error chain

type Frame

type Frame uintptr

Frame represents a program counter inside a stack frame.

func Stack

func Stack() Frame

Stack returns a stack from for parsing into a trace line

func StackLevel

func StackLevel(level int) Frame

StackLevel returns a stack from for parsing into a trace line this is primarily used by other libraries who use this package internally as the level needs to be adjusted.

func (Frame) Format

func (f Frame) Format(s fmt.State, verb rune)

Format formats the frame according to the fmt.Formatter interface.

%s    source file
%d    source line
%n    function name
%v    equivalent to %s:%d

Format accepts flags that alter the printing of some verbs, as follows:

%+s   function name and path of source file relative to the compile time
      GOPATH separated by \n\t (<funcname>\n\t<path>)
%+v   equivalent to %+s:%d

type Helper added in v1.2.0

type Helper func(Chain, error) bool

Helper is a function which will automatically extract Type and Tag information based on the supplied err and add it to the supplied *Link error; this can be used independently or by registering using errors.REgisterHelper(...), which will run the registered helper every time errors.Wrap(...) is called.

type Link struct {

	// Err is the wrapped error, either the original or already wrapped
	Err error

	// Prefix contains the error prefix text
	Prefix string

	// Type stores one or more categorized types of error set by the caller using AddTypes and is optional
	Types []string

	// Tags contains an array of tags associated with this error, if any
	Tags []Tag

	// Source contains the name, file and lines obtained from the stack trace
	Source string
}

Link contains a single error entry, unless it's the top level error, in which case it only contains an array of errors

type Tag

type Tag struct {
	Key   string
	Value interface{}
}

Tag contains a single key value conbination to be attached to your error

func T

func T(key string, value interface{}) Tag

T is a shortcut to make a Tag

Directories

Path Synopsis
_examples
helpers

Jump to

Keyboard shortcuts

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