oerrs

package module
v0.0.0-...-05c2568 Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2023 License: MIT Imports: 8 Imported by: 6

README

oerrs

Go Reference GitHub go.mod Go version

oerrs is a package for Go that builds on top of golang.org/x/xerrors.

Adds an ErrorList with optional stack traces.

Installation and Docs

Install using go get go.oneofone.dev/oerrs.

Package documentation: https://pkg.go.dev/go.oneofone.dev/oerrs

Requires go version 1.18 or newer

Features

  • Passes through most golang.org/x/xerrors functions and interfaces to make life easier.
  • A complete drop-in replacement for xerrors
  • A complete drop-in replacement for errgroup
  • ErrorList handles multiple errors in a sane way.
  • ErrorList can optionally be toggled to enable thread safety.
  • Try/Catch needs doc.
  • All errors can support be toggled to support JSON output.

Usage

oerrs was made to make error handling easier

Examples

var errs oerrs.ErrorList

errs.PushIf(step1())
errs.PushIf(step2())
if errs.PushIf(step3()) {
	// do something
}
return errs.Err()

oerrs.ErrorList implements error


if err := something(); err != nil {
	if el, ok := err.(*oerrs.ErrorList); ok {
		// Use merr.Errors
	}
	// or
	var el *oerrs.ErrorList
	if errors.As(err, &el) {
		// use el.Errors
	}
}


// try / catch

func doStuff() (res Response, err error) {
	defer oerrs.Catch(&err, nil)

	a := Try1(someFunThatReturnValAndErr())
	// do something with a
	b := Try1(someOtherFunc(a))

	return a + b, nil
}

License

The code of errgroup is mostly copied from golang.org/x/sync for personal convience, all rights reserved to go devs.

MIT

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	AlwaysWithCaller                  = true
	WrappedErrorTextIncludesFrameInfo = false
)
View Source
var CatchAll func(err error, fr *Frame)

Functions

func As

func As(err error, target interface{}) bool

As is an alias to errors.As

func Catch

func Catch(err *error, handler func(err error, fr *Frame))

func ErrorCallerf

func ErrorCallerf(skip int, format string, args ...interface{}) error

func Errorf

func Errorf(format string, args ...interface{}) error

func Is

func Is(err, target error) bool

Is is an alias to errors.Is

func Join

func Join(errs ...error) error

func New

func New(s string) error

func Opaque

func Opaque(err error) error

Opaque is an alias to xerrors.Opaque

func Try

func Try(err error)

func Try1

func Try1[T1 any](v1 T1, err error) T1

func Try2

func Try2[T1, T2 any](v1 T1, v2 T2, err error) (T1, T2)

func Try3

func Try3[T1, T2, T3 any](v1 T1, v2 T2, v3 T3, err error) (T1, T2, T3)

func Try4

func Try4[T1, T2, T3, T4 any](v1 T1, v2 T2, v3 T3, v4 T4, err error) (T1, T2, T3, T4)

func Try5

func Try5[T1, T2, T3, T4, T5 any](v1 T1, v2 T2, v3 T3, v4 T4, v5 T5, err error) (T1, T2, T3, T4, T5)

func Unwrap

func Unwrap(err error) error

Unwrap is an alias to errors.Unwrap

func Wrap

func Wrap(err error, skip int) error

Types

type ErrorList

type ErrorList struct {
	// contains filtered or unexported fields
}

func NewList

func NewList() *ErrorList

func NewSafeList

func NewSafeList(includeCallers bool) *ErrorList

func (*ErrorList) As

func (e *ErrorList) As(target interface{}) bool

As implements errors.As by checking if target is ErrorList, otherwise will go through each error.

func (*ErrorList) Err

func (e *ErrorList) Err() error

func (*ErrorList) Error

func (e *ErrorList) Error() string

Error implements the error interface

func (*ErrorList) ErrorCallerf

func (e *ErrorList) ErrorCallerf(skip int, format string, args ...interface{})

func (*ErrorList) Errorf

func (e *ErrorList) Errorf(format string, args ...interface{})

func (*ErrorList) Errors

func (e *ErrorList) Errors() []error

func (*ErrorList) Is

func (e *ErrorList) Is(target error) bool

Is implements errors.Is by comparing if target is ErrorList, otherwise will go through each error.

func (*ErrorList) PushCallerIf

func (e *ErrorList) PushCallerIf(err error, skip int) bool

func (*ErrorList) PushIf

func (e *ErrorList) PushIf(err error) bool

func (*ErrorList) Reset

func (e *ErrorList) Reset()

func (*ErrorList) Safe

func (e *ErrorList) Safe()

func (*ErrorList) Unwrap

func (e *ErrorList) Unwrap() error

Unwrap implements errors.Unwrap by returning the next error in the chain or nil if there are no more errors.

type Formatter

type Formatter = xerrors.Formatter

type aliases from xerrors

type Frame

type Frame struct {
	runtime.Frame
	// contains filtered or unexported fields
}

A Frame contains part of a call stack. Copied from xerrors

func Caller

func Caller(skip int) *Frame

Caller returns a Frame that describes a frame on the caller's stack. The argument skip is the number of frames to skip over. Caller(0) returns the frame for the caller of Caller.

func Unframe

func Unframe(err error) (*Frame, error)

func (*Frame) Format

func (f *Frame) Format(p Printer)

Format prints the stack as error detail. It should be called from an error's Format implementation after printing any other error detail.

func (*Frame) Location

func (fr *Frame) Location() (function, file string, line int)

location reports the file, line, and function of a frame.

The returned function may be "" even if file and line are not.

func (*Frame) String

func (f *Frame) String() string

type Framer

type Framer interface {
	Frame() *Frame
}

type Group

type Group struct {
	// contains filtered or unexported fields
}

A Group is a collection of goroutines working on subtasks that are part of the same overall task.

A zero Group is valid and does not cancel on error.

Example (JustErrors)

JustErrors illustrates the use of a Group in place of a sync.WaitGroup to simplify goroutine counting and error handling. This example is derived from the sync.WaitGroup example at https://golang.org/pkg/sync/#example_WaitGroup.

g := new(Group)
urls := []string{
	"http://www.golang.org/",
	"http://www.google.com/",
	"http://www.somestupidname.com/",
}
for _, url := range urls {
	// Launch a goroutine to fetch the URL.
	url := url // https://golang.org/doc/faq#closures_and_goroutines
	g.Go(func() error {
		// Fetch the URL.
		resp, err := http.Get(url)
		if err == nil {
			resp.Body.Close()
		}
		return err
	})
}
// Wait for all HTTP fetches to complete.
if err := g.Wait(); err == nil {
	fmt.Println("Successfully fetched all URLs.")
}
Output:

Example (Parallel)

Parallel illustrates the use of a Group for synchronizing a simple parallel task: the "Google Search 2.0" function from https://talks.golang.org/2012/concurrency.slide#46, augmented with a Context and error-handling.

Google := func(ctx context.Context, query string) ([]Result, error) {
	g, ctx := GroupWithContext(ctx)

	searches := []Search{Web, Image, Video}
	results := make([]Result, len(searches))
	for i, search := range searches {
		i, search := i, search // https://golang.org/doc/faq#closures_and_goroutines
		g.Go(func() error {
			result, err := search(ctx, query)
			if err == nil {
				results[i] = result
			}
			return err
		})
	}
	if err := g.Wait(); err != nil {
		return nil, err
	}
	return results, nil
}

results, err := Google(context.Background(), "golang")
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
for _, result := range results {
	fmt.Println(result)
}
Output:

web result for "golang"
image result for "golang"
video result for "golang"

func GroupWithContext

func GroupWithContext(ctx context.Context) (*Group, context.Context)

WithContext returns a new Group and an associated Context derived from ctx.

The derived Context is canceled the first time a function passed to Go returns a non-nil error or the first time Wait returns, whichever occurs first.

func (*Group) Go

func (g *Group) Go(f func() error)

Go calls the given function in a new goroutine. It blocks until the new goroutine can be added without the number of active goroutines in the group exceeding the configured limit.

The first call to return a non-nil error cancels the group; its error will be returned by Wait.

func (*Group) SetLimit

func (g *Group) SetLimit(n int)

SetLimit limits the number of active goroutines in this group to at most n. A negative value indicates no limit.

Any subsequent call to the Go method will block until it can add an active goroutine without exceeding the configured limit.

The limit must not be modified while any goroutines in the group are active.

func (*Group) TryGo

func (g *Group) TryGo(f func() error) bool

TryGo calls the given function in a new goroutine only if the number of active goroutines in the group is currently below the configured limit.

The return value reports whether the goroutine was started.

func (*Group) Wait

func (g *Group) Wait() error

Wait blocks until all function calls from the Go method have returned, then returns the first non-nil error (if any) from them.

func (*Group) WithContext

func (g *Group) WithContext(ctx context.Context) context.Context

type HasAs

type HasAs interface {
	As(interface{}) bool
}

HasAs is a handy interface to check if an error implements As

type HasIs

type HasIs interface {
	Is(error) bool
}

HasIs is a handy interface to check if an error implements Is

type JSONError

type JSONError struct {
	Err  string `json:"error,omitempty"`
	Func string `json:"func,omitempty"`
	File string `json:"file,omitempty"`
	Line int    `json:"line,omitempty"`
	// contains filtered or unexported fields
}

func (*JSONError) Error

func (e *JSONError) Error() string

func (*JSONError) Format

func (e *JSONError) Format(s fmt.State, v rune)

func (*JSONError) FormatError

func (e *JSONError) FormatError(p Printer) (next error)

func (*JSONError) Frame

func (e *JSONError) Frame() *Frame

func (*JSONError) Is

func (e *JSONError) Is(target error) bool

func (*JSONError) MarshalJSON

func (e *JSONError) MarshalJSON() ([]byte, error)

func (*JSONError) Unwrap

func (e *JSONError) Unwrap() error

type Printer

type Printer = xerrors.Printer

type aliases from xerrors

type String

type String string

String is a plain string error, it can be converted to string and compared

func (String) Error

func (e String) Error() string

func (String) Is

func (e String) Is(o error) bool

func (String) WithFrame

func (e String) WithFrame(skip int) error

type Wrapper

type Wrapper = xerrors.Wrapper

type aliases from xerrors

Jump to

Keyboard shortcuts

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