errors

package module
v2.2.1 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: 2

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.v2"

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);
Enhancements
  • New(msg, args...) combines New and Newf(if there is a name), WithMessage, WithMessagef, ...
  • WithCause(cause error, message string, args...interface{})
  • Wrap(err error, message string, args ...interface{}) error, no Wrapf
  • DumpStacksAsString(allRoutines bool): returns stack tracing information like debug.PrintStack()
  • CanXXX:
    • CanAttach(err interface{}) bool
    • CanCause(err interface{}) bool
    • CanUnwrap(err interface{}) bool
    • CanIs(err interface{}) bool
    • CanAs(err interface{}) bool
Extras
  • Container/Holder for a group of sub-errors
  • Coded error: the predefined errno

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).Message("some tips %v", "here").Build()
	t.Logf("failed: %+v", err)
}

error Container and sub-errors (wrapped, attached or nested)

  • NewContainer(message string, args ...interface{}) *withCauses
  • ContainerIsEmpty(container error) bool
  • AttachTo(container *withCauses, errs ...error)
  • withCauses.Attach(errs ...error)

For example:

func a() (err error){
    container = errors.NewContainer("sample error")
    defer container.Defer(&err) // wraps the errors in container to err and return it

    // ...
    for {
        // ...
        // in a long loop, we can add many sub-errors into container 'c'...
        errors.AttachTo(container, io.EOF, io.ErrUnexpectedEOF, io.ErrShortBuffer, io.ErrShortWrite)
        // Or:
        // container.Attach(someFuncReturnsErr(xxx))
        // ... break
    }
    // // and we extract all of them as a single parent error object now.
    // err = container.Error()
    return
}

func b(){
    err := a()
    // test the containered error 'err' if it hosted a sub-error `io.ErrShortWrite` or not.
    if errors.Is(err, io.ErrShortWrite) {
        panic(err)
    }
}

Coded error

  • Code is a generic type of error codes
  • WithCode(code, err, msg, args...) can format an error object with error code, attached inner err, message or msg template, and stack info.
  • Code.New(msg, args...) is like WithCode.
  • Code.Register(codeNameString) declares the name string of an error code yourself.
  • Code.NewTemplate(tmpl) create an coded error template object *WithCodeInfo.
  • WithCodeInfo.FormateNew(livedArgs...) formats the err msg till used.
  • Equal(err, code): compares err with code

Try it at: https://play.golang.org/p/Y2uThZHAvK1

Builtin Codes

The builtin Codes are errors, such as OK, Canceled, Unknown, InvalidArgument, DeadlineExceeded, NotFound, AlreadyExists, etc..

// Uses a Code as an error
var err error = errors.OK
var err2 error = errors.InvalidArgument
fmt.Println("error is: %v", err2)

// Uses a Code as enh-error (hedzr/errors)
err := InvalidArgument.New("wrong").Attach(io.ErrShortWrite)
Customized Codes
// customizing the error code
const MyCode001 errors.Code=1001

// and register the name of MyCode001
MyCode001.Register("MyCode001")

// and use it as a builtin Code
fmt.Println("error is: %v", MyCode001)
err := MyCode001.New("wrong 001: no config file")
Error Template: formatting the coded-error late
const BUG1001 errors.Code=1001
errTmpl1001 := BUG1001.NewTemplate("something is wrong, %v")
err4 := errTmpl1001.FormatNew("unsatisfied conditions").Attach(io.ShortBuffer)
fmt.Println(err4)
fmt.Printf("%+v\n", err4)

ACK

  • stack.go is an copy from pkg/errors
  • withStack is an copy from pkg/errors
  • Is, As, Unwrap are inspired from go1.13 errors
  • Cause, Wrap are inspired from pkg/errors

LICENSE

MIT

Scan

FOSSA Status

Documentation

Overview

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

Example (Container)
// err := sample(false)
c := errors.NewContainer("sample error")
err := c.Error()
if err != nil {
	panic(err)
} else {
	fmt.Printf("1. want nil: %v\n", err)
}

// err = sample(true)
c = errors.NewContainer("sample error")
// in a long loop, we can add many sub-errors into container 'c'...
errors.AttachTo(c, io.EOF, io.ErrUnexpectedEOF, io.ErrShortBuffer, io.ErrShortWrite)
// and we extract all of them as a single parent error object now.
err = c.Error()
if err == nil {
	panic("want error")
} else {
	fmt.Printf("2. %v\n", err)
}

// Example output:
// 1. want nil: <nil>
// 2. [EOF, unexpected EOF, short buffer, short write]
Output:

Example (ErrorCode)
err := errors.InvalidArgument.New("wrong").Attach(io.ErrShortWrite)
fmt.Println(err)
fmt.Printf("%+v\n", err)

if !errors.Is(err, io.ErrShortWrite) {
	panic("wrong Is()")
}
if errors.Is(err, io.EOF) {
	panic("wrong Is()")
}

// Example output:
// INVALID_ARGUMENT|wrong|short write
// -3|INVALID_ARGUMENT|wrong|short write
// gopkg.in/hedzr/errors%2ev2.Code.New
// /Users/hz/hzw/golang-dev/src/github.com/hedzr/errors/coded.go:365
// gopkg.in/hedzr/errors%2ev2_test.Example_errorCode
// /Users/hz/hzw/golang-dev/src/github.com/hedzr/errors/example_test.go:50
// gopkg.in/hedzr/errors%2ev2_test.TestForExamples
// /Users/hz/hzw/golang-dev/src/github.com/hedzr/errors/example_test.go:11
// testing.tRunner
// /usr/local/opt/go/libexec/src/testing/testing.go:909
// runtime.goexit
// /usr/local/opt/go/libexec/src/runtime/asm_amd64.s:1357
Output:

Example (ErrorCodeCustom)
const ErrnoMyFault errors.Code = 1101
ErrnoMyFault.Register("MyFault")
fmt.Printf("%+v\n", ErrnoMyFault)

err := ErrnoMyFault.New("my fault message")
fmt.Printf("%+v\n", err)

// Example output:
// MyFault
// 1101|MyFault|my fault message
// gopkg.in/hedzr/errors%2ev2.Code.New
// /Users/hz/hzw/golang-dev/src/github.com/hedzr/errors/coded.go:365
// gopkg.in/hedzr/errors%2ev2_test.Example_errorCodeCustom
// /Users/hz/hzw/golang-dev/src/github.com/hedzr/errors/example_test.go:80
// gopkg.in/hedzr/errors%2ev2_test.TestForExamples
// /Users/hz/hzw/golang-dev/src/github.com/hedzr/errors/example_test.go:11
// testing.tRunner
// /usr/local/opt/go/libexec/src/testing/testing.go:909
// runtime.goexit
// /usr/local/opt/go/libexec/src/runtime/asm_amd64.s:1357
Output:

Example (ErrorTemplate)
const ErrnoMyFault errors.Code = 1101
ErrnoMyFault.Register("MyFault")

tmpl := ErrnoMyFault.NewTemplate("my fault message: %v")
err := tmpl.FormatNew("whoops")
fmt.Printf("%+v\n", err)

// Example output:
// 1101|MyFault|my fault message: whoops
// gopkg.in/hedzr/errors%2ev2.(*WithCodeInfo).FormatNew
// /Users/hz/hzw/golang-dev/src/github.com/hedzr/errors/coded.go:270
// gopkg.in/hedzr/errors%2ev2_test.Example_errorTemplate
// /Users/hz/hzw/golang-dev/src/github.com/hedzr/errors/example_test.go:106
// gopkg.in/hedzr/errors%2ev2_test.TestForExamples
// /Users/hz/hzw/golang-dev/src/github.com/hedzr/errors/example_test.go:14
// testing.tRunner
// /usr/local/opt/go/libexec/src/testing/testing.go:909
// runtime.goexit
// /usr/local/opt/go/libexec/src/runtime/asm_amd64.s:1357
Output:

Index

Examples

Constants

View Source
const (
	// AppName const
	AppName = "errors"
	// Version const
	Version = "2.2.0"
	// VersionInt const
	VersionInt = 0x020200
)

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 added in v2.1.0

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

AsSlice tests err.As for errs slice

func AttachTo

func AttachTo(container *WithCauses, errs ...error)

AttachTo appends more errors into 'container' error container.

func CanAs

func CanAs(err interface{}) (ok bool)

CanAs tests if err is as-able

func CanAttach

func CanAttach(err interface{}) (ok bool)

CanAttach tests if err is attach-able

func CanCause

func CanCause(err interface{}) (ok bool)

CanCause tests if err is cause-able

func CanIs

func CanIs(err interface{}) (ok bool)

CanIs tests if err is is-able

func CanUnwrap

func CanUnwrap(err interface{}) (ok bool)

CanUnwrap tests if err is unwrap-able

func Cause

func Cause(err error) error

Cause returns the underlying cause of the error recursively, 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 Cause1

func Cause1(err error) error

Cause1 returns the underlying cause of the error, if possible. Cause1 unwraps just one level of the inner wrapped error.

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 ContainerIsEmpty

func ContainerIsEmpty(container error) bool

ContainerIsEmpty tests if 'container' is empty (no more wrapped/attached sub-errors)

func DumpStacksAsString

func DumpStacksAsString(allRoutines bool) string

DumpStacksAsString returns stack tracing information like debug.PrintStack()

func Equal added in v2.0.11

func Equal(err error, code Code) bool

Equal compares error object and error Code

func EqualR added in v2.0.11

func EqualR(err error, code Code) bool

EqualR compares error object and error Code recursively

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 added in v2.1.0

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

IsSlice tests err.Is for errs slice

func Message added in v2.2.1

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 Skip added in v2.2.1

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()

func TypeIs added in v2.1.9

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 added in v2.1.9

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 WithCause

func WithCause(cause error, message string, args ...interface{}) error

WithCause is synonym of Wrap

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 Code added in v2.0.5

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 added in v2.1.3

func (c Code) Error() string

Error for error interface

func (Code) New added in v2.0.5

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

New create a new *CodedErr object based an error code

func (Code) NewTemplate added in v2.0.8

func (c Code) NewTemplate(tmpl string) *WithCodeInfo

NewTemplate create an error template so that you may `FormatNew(liveArgs...)` late.

func (Code) Register added in v2.0.5

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

Register registers a code and its token string for using later

func (Code) String added in v2.0.5

func (c Code) String() string

String for stringer 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 Holder added in v2.0.13

Holder is an interface for WithCauses and InterfaceContainer

type InterfaceAttach added in v2.0.13

type InterfaceAttach interface {
	// Attach appends errs
	Attach(errs ...error)
}

InterfaceAttach is an interface with Attach

type InterfaceAttachCause added in v2.2.1

type InterfaceAttachCause interface {
	// Attach sets the underlying error manually if necessary.
	Attach(cause error) error
}

InterfaceAttachCause _

type InterfaceAttachCauses added in v2.2.1

type InterfaceAttachCauses interface {
	Attach(causes ...error) error
}

InterfaceAttachCauses _

type InterfaceAttachSpecial added in v2.0.13

type InterfaceAttachSpecial interface {
	// Attach appends errs
	Attach(errs ...error) *WithStackInfo
}

InterfaceAttachSpecial is an interface with Attach

type InterfaceCause added in v2.0.13

type InterfaceCause interface {
	// 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.
	Cause() error
}

InterfaceCause is an interface with Cause

type InterfaceCauses added in v2.0.13

type InterfaceCauses interface {
	Causes() []error
}

InterfaceCauses is an interface with Causes

type InterfaceContainer added in v2.0.13

type InterfaceContainer interface {
	// IsEmpty tests has attached errors
	IsEmpty() bool
}

InterfaceContainer is an interface with IsEmpty

type InterfaceFormat added in v2.0.13

type InterfaceFormat interface {
	// 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.
	Format(s fmt.State, verb rune)
}

InterfaceFormat is an interface with Format

type InterfaceIsAsUnwrap added in v2.0.13

type InterfaceIsAsUnwrap interface {
	// Is reports whether any error in err's chain matches target.
	Is(target error) 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.
	As(target interface{}) bool
	// 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.
	Unwrap() error
}

InterfaceIsAsUnwrap is an interface with Is, As, and Unwrap

type InterfaceSetCause added in v2.2.1

type InterfaceSetCause interface {
	// SetCause sets the underlying error manually if necessary.
	SetCause(cause error) error
}

InterfaceSetCause _

type InterfaceWithStackInfo added in v2.0.13

InterfaceWithStackInfo is an interface for WithStackInfo

type Stack added in v2.0.7

type Stack []uintptr

Stack represents a Stack of program counters.

func (*Stack) Format added in v2.0.7

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 added in v2.0.7

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 WithCauses added in v2.0.7

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

WithCauses holds a group of errors object.

func NewContainer

func NewContainer(message string, args ...interface{}) *WithCauses

NewContainer wraps a group of errors and msg as one and return it. The returned error object is a container to hold many sub-errors.

For Example:

c := errors.NewContainer("sample error")
... for a long loop
errors.AttachTo(c, io.EOF, io.ErrUnexpectedEOF, io.ErrShortBuffer, io.ErrShortWrite)
...
err = c.Error()

func (*WithCauses) As added in v2.0.13

func (w *WithCauses) 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 (*WithCauses) Attach added in v2.0.7

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

Attach appends errs

func (*WithCauses) Cause added in v2.0.7

func (w *WithCauses) 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 (*WithCauses) Causes added in v2.0.7

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

Causes returns the underlying cause of the errors.

func (*WithCauses) Defer added in v2.2.0

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

func (*WithCauses) Error added in v2.0.7

func (w *WithCauses) Error() error

func (*WithCauses) Is added in v2.0.7

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

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

func (*WithCauses) IsEmpty added in v2.0.7

func (w *WithCauses) IsEmpty() bool

IsEmpty tests has attached errors

func (*WithCauses) SetCause added in v2.0.13

func (w *WithCauses) SetCause(cause error) error

SetCause sets the underlying error manually if necessary.

func (*WithCauses) TypeIs added in v2.1.9

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

func (*WithCauses) Unwrap added in v2.0.7

func (w *WithCauses) Unwrap() 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.

type WithCodeInfo added in v2.0.8

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

WithCodeInfo is a type integrating both error code, cause, message, and template

func (*WithCodeInfo) As added in v2.0.10

func (w *WithCodeInfo) 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 (*WithCodeInfo) Attach added in v2.0.8

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

Attach appends errs

func (*WithCodeInfo) Cause added in v2.0.8

func (w *WithCodeInfo) Cause() error

Cause returns the underlying cause of the error recursively, if possible.

func (*WithCodeInfo) Code added in v2.0.11

func (w *WithCodeInfo) Code() Code

Code returns the error code value

func (*WithCodeInfo) Equal added in v2.0.11

func (w *WithCodeInfo) Equal(c Code) bool

Equal tests if equals with code 'c'

func (*WithCodeInfo) Error added in v2.0.8

func (w *WithCodeInfo) Error() string

func (*WithCodeInfo) Format added in v2.0.10

func (w *WithCodeInfo) 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 (*WithCodeInfo) FormatNew added in v2.0.8

func (w *WithCodeInfo) FormatNew(livedArgs ...interface{}) *WithStackInfo

FormatNew creates a new error object based on this error template 'w'.

Example:

errTmpl1001 := BUG1001.NewTemplate("something is wrong %v")
err4 := errTmpl1001.FormatNew("ok").Attach(errBug1)
fmt.Println(err4)
fmt.Printf("%+v\n", err4)

func (*WithCodeInfo) Is added in v2.0.8

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

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

func (*WithCodeInfo) TypeIs added in v2.1.9

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

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

func (*WithCodeInfo) Unwrap added in v2.0.8

func (w *WithCodeInfo) Unwrap() 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.

type WithStackInfo added in v2.0.7

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

WithStackInfo is exported now

func New

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

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

Example
err := errors.New("whoops")
fmt.Println(err)
Output:

whoops

func WithCode added in v2.0.5

func WithCode(code Code, err error, message string, args ...interface{}) *WithStackInfo

WithCode formats a wrapped error object with error code.

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.

Example
cause := errors.New("whoops")
err := errors.Wrap(cause, "oh noes")
fmt.Println(err)
Output:

oh noes: whoops
Example (Extended)
// err := fn()
e1 := errors.New("error")
e2 := errors.Wrap(e1, "inner")
e3 := errors.Wrap(e2, "middle")
err := errors.Wrap(e3, "outer")
fmt.Printf("%v\n", err)
fmt.Printf("%+v\n", err)

// Example output:
// outer: middle: inner: error
// outer: middle: inner: error
// gopkg.in/hedzr/errors%2ev2_test.fn
// /Users/hz/hzw/golang-dev/src/github.com/hedzr/errors/example_test.go:136
// gopkg.in/hedzr/errors%2ev2_test.ExampleWrap_extended
// /Users/hz/hzw/golang-dev/src/github.com/hedzr/errors/example_test.go:148
// gopkg.in/hedzr/errors%2ev2_test.TestForExamples
// /Users/hz/hzw/golang-dev/src/github.com/hedzr/errors/example_test.go:15
// testing.tRunner
// /usr/local/opt/go/libexec/src/testing/testing.go:909
// runtime.goexit
// /usr/local/opt/go/libexec/src/runtime/asm_amd64.s:1357
Output:

func (*WithStackInfo) As added in v2.0.7

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 added in v2.0.7

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

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

func (*WithStackInfo) AttachGenerals added in v2.2.0

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

AttachGenerals appends errs if the general object is a error object WithStackInfo.AttachGenerals() can only wrap and hold one child error object.

func (*WithStackInfo) Cause added in v2.0.7

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) Format added in v2.0.7

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 added in v2.0.7

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

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

func (*WithStackInfo) IsEmpty added in v2.0.7

func (w *WithStackInfo) IsEmpty() bool

IsEmpty tests has attached errors

func (*WithStackInfo) SetCause added in v2.0.7

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

SetCause sets the underlying error manually if necessary.

func (*WithStackInfo) TypeIs added in v2.1.9

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

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

func (*WithStackInfo) Unwrap added in v2.0.7

func (w *WithStackInfo) Unwrap() 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.

Jump to

Keyboard shortcuts

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