errors

package module
v3.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2022 License: MIT Imports: 7 Imported by: 38

README

errors.v2

Build Status GitHub tag (latest SemVer) GoDoc Go Report Card codecov FOSSA Status

Wrapped errors and more for golang developing (not just for go1.13+).

hedzr/errors provides the compatbilities to your old project up to go 1.13.

hedzr/errors provides some extra enhancements for better context environment saving on error occurred.

Import

// wrong: import "github.com/hedzr/errors/v2"
import "gopkg.in/hedzr/errors.v3"

Features

stdlib `errors' compatibilities
  • func As(err error, target interface{}) bool
  • func Is(err, target error) bool
  • func New(text string) error
  • func Unwrap(err error) error
pkg/errors compatibilities
  • func Wrap(err error, message string) error
  • func Cause(err error) error: unwraps recursively, just like Unwrap()
  • func Cause1(err error) error: unwraps just one level
  • func WithCause(cause error, message string, args ...interface{}) error, = Wrap
  • supports Stacktrace
    • in an error by Wrap(), stacktrace wrapped;
    • for your error, attached by WithStack(cause error);
Others
  • Codes
  • Inner errors
  • Unwrap inner errors one by one

Best Practices

package test

import (
	"gopkg.in/hedzr/errors.v2"
	"io"
	"testing"
)

func TestForExample(t *testing.T) {

	err := errors.New("some tips %v", "here")

	// attaches much more errors
	for _, e := range []error{io.EOF, io.ErrClosedPipe} {
		_ = err.Attach(e)
	}

	t.Logf("failed: %+v", err)

	// use another number different to default to skip the error frames
	err = errors.
		Skip(3). // from on Skip()
		WithMessage("some tips %v", "here").Build()
	t.Logf("failed: %+v", err)

	err = errors.
		Message("1"). // from Message() on
		WithSkip(0).
		WithMessage("bug msg").
		Build()
	t.Logf("failed: %+v", err)

	err = errors.
		NewBuilder(). // from NewBuilder() on
		WithCode(errors.Internal). // add errors.Code
		WithErrors(io.EOF). // attach inner errors
		WithErrors(io.ErrShortWrite, io.ErrClosedPipe).
		Build()
	t.Logf("failed: %+v", err)

	// As code
	var c1 errors.Code
	if errors.As(err, &c1) {
		println(c1) // = Internal
	}

	// As inner errors
	var a1 []error
	if errors.As(err, &a1) {
		println(len(a1)) // = 3, means [io.EOF, io.ErrShortWrite, io.ErrClosedPipe]
	}

	// As error, the first inner error will be extracted
	var ee1 error
	if errors.As(err, &ee1) {
		println(ee1) // = io.EOF
	}
	
	series := []error{io.EOF, io.ErrShortWrite, io.ErrClosedPipe, errors.Internal}
	var index int
	for ; ee1 != nil; index++ {
		ee1 = errors.Unwrap(err) // extract the inner errors one by one
		if ee1 != nil && ee1 != series[index] {
			t.Fatalf("%d. cannot extract '%v' error with As(), ee1 = %v", index, series[index], ee1)
		}
	}
}

func TestContainer(t *testing.T) {
	// as a inner errors container
	child := func() (err error) {
		errContainer := errors.New("")

		defer errContainer.Defer(&err)
		for _, r:=range []error{io.EOF, io.ErrShortWrite, io.ErrClosedPipe, errors.Internal} {
			errContainer.Attach(r)
		}

		return
	}

	err := child()
	t.Logf("failed: %+v", err)
}

LICENSE

MIT

Scan

FOSSA Status

Documentation

Overview

Package errors provides some error handling primitives for wrapped, coded, messaged errors.

Index

Constants

View Source
const (
	// AppName const
	AppName = "errors"
	// Version const
	Version = "3.0.0"
	// VersionInt const
	VersionInt = 0x030000
)

Variables

This section is empty.

Functions

func As

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

As finds the first error in `err`'s chain that matches target, and if so, sets target to that error value and returns true.

The chain consists of err itself followed by the sequence of errors obtained by repeatedly calling Unwrap.

An error matches target if the error's concrete value is assignable to the value pointed to by target, or if the error has a method As(interface{}) bool such that As(target) returns true. In the latter case, the As method is responsible for setting target.

As will panic if target is not a non-nil pointer to either a type that implements error, or to any interface type. As returns false if err is nil.

func AsSlice

func AsSlice(errs []error, target interface{}) bool

AsSlice tests err.As for errs slice

func Is

func Is(err, target error) bool

Is reports whether any error in `err`'s chain matches target.

The chain consists of err itself followed by the sequence of errors obtained by repeatedly calling Unwrap.

An error is considered to match a target if it is equal to that target or if it implements a method Is(error) bool such that Is(target) returns true.

func IsSlice

func IsSlice(errs []error, target error) bool

IsSlice tests err.Is for errs slice

func TypeIs

func TypeIs(err, target error) bool

TypeIs reports whether any error in `err`'s chain matches target.

The chain consists of err itself followed by the sequence of errors obtained by repeatedly calling Unwrap.

An error is considered to match a target if it is equal to that target or if it implements a method Is(error) bool such that Is(target) returns true.

func TypeIsSlice

func TypeIsSlice(errs []error, target error) bool

TypeIsSlice tests err.Is for errs slice

func Unwrap

func Unwrap(err error) error

Unwrap returns the result of calling the Unwrap method on err, if `err`'s type contains an Unwrap method returning error. Otherwise, Unwrap returns nil.

func WithStack

func WithStack(cause error) error

WithStack annotates err with a Stack trace at the point WithStack was called. If err is nil, WithStack returns nil.

Types

type Builder

type Builder interface {
	// WithSkip specifies a special number of stack frames that will be ignored.
	WithSkip(skip int) Builder
	// WithErrors attaches the given errs as inner errors.
	WithErrors(errs ...error) Builder
	// WithMessage formats the error message
	WithMessage(message string, args ...interface{}) Builder
	// WithCode specifies an error code.
	WithCode(code Code) Builder
	// Build builds the final error object (with *WithStackInfo type wrapped)
	Build() *WithStackInfo
}

Builder provides a fluent calling interface to make error building easy.

func Message

func Message(message string, args ...interface{}) Builder

Message formats a message and starts a builder to create the final error object.

err := errors.Message("hello %v", "you").Attach(causer).Build()

func NewBuilder

func NewBuilder() Builder

NewBuilder starts a new error builder.

Typically, you could make an error with fluent calls:

err = errors.NewBuilder().
	WithCode(Internal).
	WithErrors(io.EOF).
	WithErrors(io.ErrShortWrite).
	Build()
t.Logf("failed: %+v", err)

func Skip

func Skip(skip int) Builder

Skip sets how many frames will be ignored while we are extracting the stacktrace info. Skip starts a builder with fluent API style, so you could continue build the error what you want:

err := errors.Skip(1).Message("hello %v", "you").Build()

type Code

type Code int32

A Code is an signed 32-bit error code copied from gRPC spec but negatived.

const (
	// OK is returned on success.
	OK Code = 0

	// Canceled indicates the operation was canceled (typically by the caller).
	Canceled Code = -1

	// Unknown error. An example of where this error may be returned is
	// if a Status value received from another address space belongs to
	// an error-space that is not known in this address space. Also
	// errors raised by APIs that do not return enough error information
	// may be converted to this error.
	Unknown Code = -2

	// InvalidArgument indicates client specified an invalid argument.
	// Note that this differs from FailedPrecondition. It indicates arguments
	// that are problematic regardless of the state of the system
	// (e.g., a malformed file name).
	InvalidArgument Code = -3

	// DeadlineExceeded means operation expired before completion.
	// For operations that change the state of the system, this error may be
	// returned even if the operation has completed successfully. For
	// example, a successful response from a server could have been delayed
	// long enough for the deadline to expire.
	//
	// = HTTP 408 Timeout
	DeadlineExceeded Code = -4

	// NotFound means some requested entity (e.g., file or directory) was
	// not found.
	//
	// = HTTP 404
	NotFound Code = -5

	// AlreadyExists means an attempt to create an entity failed because one
	// already exists.
	AlreadyExists Code = -6

	// PermissionDenied indicates the caller does not have permission to
	// execute the specified operation. It must not be used for rejections
	// caused by exhausting some resource (use ResourceExhausted
	// instead for those errors). It must not be
	// used if the caller cannot be identified (use Unauthenticated
	// instead for those errors).
	PermissionDenied Code = -7

	// ResourceExhausted indicates some resource has been exhausted, perhaps
	// a per-user quota, or perhaps the entire file system is out of space.
	ResourceExhausted Code = -8

	// FailedPrecondition indicates operation was rejected because the
	// system is not in a state required for the operation's execution.
	// For example, directory to be deleted may be non-empty, an rmdir
	// operation is applied to a non-directory, etc.
	//
	// A litmus test that may help a service implementor in deciding
	// between FailedPrecondition, Aborted, and Unavailable:
	//  (a) Use Unavailable if the client can retry just the failing call.
	//  (b) Use Aborted if the client should retry at a higher-level
	//      (e.g., restarting a read-modify-write sequence).
	//  (c) Use FailedPrecondition if the client should not retry until
	//      the system state has been explicitly fixed. E.g., if an "rmdir"
	//      fails because the directory is non-empty, FailedPrecondition
	//      should be returned since the client should not retry unless
	//      they have first fixed up the directory by deleting files from it.
	//  (d) Use FailedPrecondition if the client performs conditional
	//      REST Get/Update/Delete on a resource and the resource on the
	//      server does not match the condition. E.g., conflicting
	//      read-modify-write on the same resource.
	FailedPrecondition Code = -9

	// Aborted indicates the operation was aborted, typically due to a
	// concurrency issue like sequencer check failures, transaction aborts,
	// etc.
	//
	// See litmus test above for deciding between FailedPrecondition,
	// Aborted, and Unavailable.
	Aborted Code = -10

	// OutOfRange means operation was attempted past the valid range.
	// E.g., seeking or reading past end of file.
	//
	// Unlike InvalidArgument, this error indicates a problem that may
	// be fixed if the system state changes. For example, a 32-bit file
	// system will generate InvalidArgument if asked to read at an
	// offset that is not in the range [0,2^32-1], but it will generate
	// OutOfRange if asked to read from an offset past the current
	// file size.
	//
	// There is a fair bit of overlap between FailedPrecondition and
	// OutOfRange. We recommend using OutOfRange (the more specific
	// error) when it applies so that callers who are iterating through
	// a space can easily look for an OutOfRange error to detect when
	// they are done.
	OutOfRange Code = -11

	// Unimplemented indicates operation is not implemented or not
	// supported/enabled in this service.
	Unimplemented Code = -12

	// Internal errors. Means some invariants expected by underlying
	// system has been broken. If you see one of these errors,
	// something is very broken.
	Internal Code = -13

	// Unavailable indicates the service is currently unavailable.
	// This is a most likely a transient condition and may be corrected
	// by retrying with a backoff. Note that it is not always safe to retry
	// non-idempotent operations.
	//
	// See litmus test above for deciding between FailedPrecondition,
	// Aborted, and Unavailable.
	Unavailable Code = -14

	// DataLoss indicates unrecoverable data loss or corruption.
	DataLoss Code = -15

	// Unauthenticated indicates the request does not have valid
	// authentication credentials for the operation.
	//
	// = HTTP 401 Unauthorized
	Unauthenticated Code = -16

	// RateLimited indicates some flow control algorithm is running and applied.
	// = HTTP Code 429
	RateLimited Code = -17

	// BadRequest generates a 400 error.
	// = HTTP 400
	BadRequest Code = -18

	// Conflict generates a 409 error.
	// = hTTP 409
	Conflict Code = -19

	// Forbidden generates a 403 error.
	Forbidden Code = -20

	// InternalServerError generates a 500 error.
	InternalServerError Code = -21

	// MethodNotAllowed generates a 405 error.
	MethodNotAllowed Code = -22

	// Timeout generates a Timeout error.
	Timeout Code = -23

	// MinErrorCode is the lower bound
	MinErrorCode Code = -1000
)

func (Code) Error

func (c Code) Error() string

Error for error interface

func (Code) New

func (c Code) New(msg string, args ...interface{}) *WithStackInfo

New create a new *CodedErr object based an error code

func (Code) Register

func (c Code) Register(codeName string) (errno Code)

Register registers a code and its token string for using later

func (Code) String

func (c Code) String() string

String for stringer interface

func (*Code) WithCode

func (c *Code) WithCode(code Code) *Code

WithCode for error interface

type Frame

type Frame uintptr

Frame represents a program counter inside a Stack frame.

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 Opt

type Opt func(s *builder)

Opt _

func WithErrors

func WithErrors(errs ...error) Opt

WithErrors _

type Stack

type Stack []uintptr

Stack represents a Stack of program counters.

func (*Stack) Format

func (s *Stack) Format(st fmt.State, verb rune)

Format formats the stack of Frames according to the fmt.Formatter interface.

%s	lists source files for each Frame in the stack
%v	lists the source file and line number for each Frame in the stack

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

%+v   Prints filename, function, and line number for each Frame in the stack.

func (*Stack) StackTrace

func (s *Stack) StackTrace() StackTrace

StackTrace returns the stacktrace frames

type StackTrace

type StackTrace []Frame

StackTrace is Stack of Frames from innermost (newest) to outermost (oldest).

func (StackTrace) Format

func (st StackTrace) Format(s fmt.State, verb rune)

Format formats the Stack of Frames according to the fmt.Formatter interface.

%s	lists source files for each Frame in the Stack
%v	lists the source file and line number for each Frame in the Stack

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

%+v   Prints filename, function, and line number for each Frame in the Stack.

type TaggedData

type TaggedData map[string]interface{}

TaggedData _

type WithStackInfo

type WithStackInfo struct {
	*Stack
	// contains filtered or unexported fields
}

WithStackInfo is exported now

func New

func New(args ...interface{}) *WithStackInfo

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

func Wrap

func Wrap(err error, message string, args ...interface{}) *WithStackInfo

Wrap returns an error annotating err with a Stack trace at the point Wrap is called, and the supplied message. If err is nil, Wrap returns nil.

func (*WithStackInfo) As

func (w *WithStackInfo) As(target interface{}) bool

As finds the first error in `err`'s chain that matches target, and if so, sets target to that error value and returns true.

func (*WithStackInfo) Attach

func (w *WithStackInfo) Attach(errs ...error)

func (*WithStackInfo) Cause

func (w *WithStackInfo) Cause() error

Cause returns the underlying cause of the error, if possible. An error value has a cause if it implements the following interface:

type causer interface {
       Cause() error
}

If the error does not implement Cause, the original error will be returned. If the error is nil, nil will be returned without further investigation.

func (*WithStackInfo) Causes

func (w *WithStackInfo) Causes() []error

func (*WithStackInfo) Defer

func (w *WithStackInfo) Defer(err *error)

Defer can be used as a defer function to simplify your codes.

The codes:

 func some(){
   // as a inner errors container
   child := func() (err error) {
  	errContainer := errors.New("")
  	defer errContainer.Defer(&err)

  	for _, r := range []error{io.EOF, io.ErrClosedPipe, errors.Internal} {
  		errContainer.Attach(r)
  	}

  	return
   }

   err := child()
   t.Logf("failed: %+v", err)
}

func (*WithStackInfo) End

func (w *WithStackInfo) End()

End ends the WithXXX stream calls while you dislike unwanted `err =`.

For instance, the construction of an error without warnings looks like:

err := New("hello %v", "world")
_ = err.WithErrors(io.EOF, io.ErrShortWrite).
    WithErrors(io.ErrClosedPipe).
    WithCode(Internal)

To avoid the `_ =`, you might belove with a End() call:

err := New("hello %v", "world")
err.WithErrors(io.EOF, io.ErrShortWrite).
    WithErrors(io.ErrClosedPipe).
    WithCode(Internal).
    End()

func (*WithStackInfo) Error

func (w *WithStackInfo) Error() string

func (*WithStackInfo) Format

func (w *WithStackInfo) Format(s fmt.State, verb rune)

Format formats the stack of Frames according to the fmt.Formatter interface.

%s	lists source files for each Frame in the stack
%v	lists the source file and line number for each Frame in the stack

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

%+v   Prints filename, function, and line number for each Frame in the stack.

func (*WithStackInfo) Is

func (w *WithStackInfo) Is(target error) bool

func (*WithStackInfo) IsEmpty

func (w *WithStackInfo) IsEmpty() bool

IsEmpty tests has attached errors

func (*WithStackInfo) TypeIs

func (w *WithStackInfo) TypeIs(target error) bool

func (*WithStackInfo) Unwrap

func (w *WithStackInfo) Unwrap() error

func (*WithStackInfo) WithCause

func (w *WithStackInfo) WithCause(cause error) *WithStackInfo

WithCause sets the underlying error manually if necessary.

func (*WithStackInfo) WithCode

func (w *WithStackInfo) WithCode(code Code) *WithStackInfo

WithCode for error interface

func (*WithStackInfo) WithData

func (w *WithStackInfo) WithData(errs ...interface{}) *WithStackInfo

WithData appends errs if the general object is a error object

func (*WithStackInfo) WithErrors

func (w *WithStackInfo) WithErrors(errs ...error) *WithStackInfo

WithErrors appends errs WithStackInfo.Attach() can only wrap and hold one child error object.

func (*WithStackInfo) WithMessage

func (w *WithStackInfo) WithMessage(message string, args ...interface{}) *WithStackInfo

WithMessage _

func (*WithStackInfo) WithSkip

func (w *WithStackInfo) WithSkip(skip int) *WithStackInfo

WithSkip _

func (*WithStackInfo) WithTaggedData

func (w *WithStackInfo) WithTaggedData(siteScenes TaggedData) *WithStackInfo

WithTaggedData appends errs if the general object is a error object

Jump to

Keyboard shortcuts

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