Documentation ¶
Overview ¶
Package errors provides some error handling primitives for wrapped, coded, messaged errors.
Index ¶
- Constants
- func As(err error, target interface{}) bool
- func AsSlice(errs []error, target interface{}) bool
- func CanAs(err interface{}) (ok bool)
- func CanAttach(err interface{}) (ok bool)
- func CanCause(err interface{}) (ok bool)
- func CanCauses(err interface{}) (ok bool)
- func CanIs(err interface{}) (ok bool)
- func CanUnwrap(err interface{}) (ok bool)
- func Causes(err error) (errs []error)
- func DumpStacksAsString(allRoutines bool) string
- func Is(err, target error) bool
- func IsSlice(errs []error, target error) bool
- func TypeIs(err, target error) bool
- func TypeIsSlice(errs []error, target error) bool
- func Unwrap(err error) error
- func WithStack(cause error) error
- type Attachable
- type Buildable
- type Builder
- type Code
- type Container
- type Error
- type Frame
- type Opt
- type Stack
- type StackTrace
- type TaggedData
- type WithStackInfo
- func (w *WithStackInfo) As(target interface{}) bool
- func (w *WithStackInfo) Attach(errs ...error)
- func (w *WithStackInfo) Cause() error
- func (w *WithStackInfo) Causes() []error
- func (w *WithStackInfo) Data() []interface{}
- func (w *WithStackInfo) Defer(err *error)
- func (w *WithStackInfo) End()
- func (w *WithStackInfo) Error() string
- func (w *WithStackInfo) Format(s fmt.State, verb rune)
- func (w *WithStackInfo) Is(target error) bool
- func (w *WithStackInfo) IsEmpty() bool
- func (w *WithStackInfo) Reset()
- func (w *WithStackInfo) TaggedData() TaggedData
- func (w *WithStackInfo) TypeIs(target error) bool
- func (w *WithStackInfo) Unwrap() error
- func (w *WithStackInfo) WithCause(cause error) Buildable
- func (w *WithStackInfo) WithCode(code Code) Buildable
- func (w *WithStackInfo) WithData(errs ...interface{}) Buildable
- func (w *WithStackInfo) WithErrors(errs ...error) Buildable
- func (w *WithStackInfo) WithMessage(message string, args ...interface{}) Buildable
- func (w *WithStackInfo) WithSkip(skip int) Buildable
- func (w *WithStackInfo) WithTaggedData(siteScenes TaggedData) Buildable
Constants ¶
const ( // AppName const AppName = "errors" // Version const Version = "3.0.5" // VersionInt const VersionInt = 0x030005 )
Variables ¶
This section is empty.
Functions ¶
func As ¶
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 CanAttach ¶ added in v3.0.3
func CanAttach(err interface{}) (ok bool)
CanAttach tests if err is attach-able
func CanCause ¶ added in v3.0.3
func CanCause(err interface{}) (ok bool)
CanCause tests if err is cause-able
func CanCauses ¶ added in v3.0.5
func CanCauses(err interface{}) (ok bool)
CanCauses tests if err is cause-able
func CanUnwrap ¶ added in v3.0.3
func CanUnwrap(err interface{}) (ok bool)
CanUnwrap tests if err is unwrap-able
func Causes ¶ added in v3.0.5
Causes simply returns the wrapped inner errors. It doesn't consider an wrapped Code entity is an inner error too. So if you wanna to extract any inner error objects, use errors.Unwrap for instead. The errors.Unwrap could extract all of them one by one:
var err = errors.New("hello").WithErrors(io.EOF, io.ShortBuffers) var e error = err for e != nil { e = errors.Unwrap(err) }
func DumpStacksAsString ¶ added in v3.0.3
DumpStacksAsString returns stack tracing information like debug.PrintStack()
func Is ¶
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 TypeIs ¶
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 ¶
TypeIsSlice tests err.Is for errs slice
func Unwrap ¶
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.
An errors.Error is an unwrappable error object, all its inner errors can be unwrapped in turn. Therefore it maintains an internal unwrapping index and it can't be reset externally. The only approach to clear it and make Unwrap work from head is, to keep Unwrap till this turn ending by returning nil.
Examples for Unwrap:
var err = errors.New("hello").WithErrors(io.EOF, io.ShortBuffers) var e error = err for e != nil { e = errors.Unwrap(err) // test if e is not nil and process it... }
Types ¶
type Buildable ¶ added in v3.0.5
type Buildable interface { // error interface error // WithSkip specifies a special number of stack frames that will be ignored. WithSkip(skip int) Buildable // WithMessage formats the error message WithMessage(message string, args ...interface{}) Buildable // WithCode specifies an error code. // An error code `Code` is a integer number with error interface // supported. WithCode(code Code) Buildable // WithErrors attaches the given errs as inner errors. // WithErrors is like our old Attach(). // It wraps the inner errors into underlying container and // represents them all in a singular up-level error object. // The wrapped inner errors can be retrieved with errors.Causes: // // var err = errors.New("hello").WithErrors(io.EOF, io.ShortBuffers) // var errs []error = errors.Causes(err) // // Or, use As() to extract its: // // var errs []error // errors.As(err, &errs) // // Or, use Unwrap() for its: // // var e error = err // for e != nil { // e = errors.Unwrap(err) // } // WithErrors(errs ...error) Buildable // WithData appends errs if the general object is a error object. // It can be used in defer-recover block typically. For example: // // defer func() { // if e := recover(); e != nil { // err = errors.New("[recovered] copyTo unsatisfied ([%v] %v -> [%v] %v), causes: %v", // c.indirectType(from.Type()), from, c.indirectType(to.Type()), to, e). // WithData(e) // n := log.CalcStackFrames(1) // skip defer-recover frame at first // log.Skip(n).Errorf("%v", err) // skip go-lib frames and defer-recover frame, back to the point throwing panic // } // }() // WithData(errs ...interface{}) Buildable // WithTaggedData appends user data with tag into internal container. // These data can be retrieved by WithTaggedData(siteScenes TaggedData) Buildable // WithCause sets the underlying error manually if necessary. WithCause(cause error) Buildable // End could terminate the with-build stream calls without any return value. End() // Container _ Container }
Buildable provides a fluent calling interface to make error building easy. Buildable is an error interface too.
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 Buildable interface bound) Build() Error }
Builder provides a fluent calling interface to make error building easy.
func Message ¶
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)
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 // 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 )
type Container ¶ added in v3.0.5
type Container interface { // IsEmpty tests has attached errors IsEmpty() bool // 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) // } // Defer(err *error) // Attachable _ Attachable }
Container represents an error container which can hold a group of inner errors.
type Error ¶ added in v3.0.5
type Error interface { // Buildable _ Buildable // Data returns the wrapped common user data by Buildable.WithData. // The error objects with passed Buildable.WithData will be moved // into inner errors set, so its are excluded from Data(). Data() []interface{} // TaggedData returns the wrapped tagged user data by // Buildable.WithTaggedData. TaggedData() TaggedData // 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 an error object does not implement Cause interface, the // original error object will be returned. // If the error is nil, nil will be returned without further // investigation. Cause() error // Causes simply returns the wrapped inner errors. // It doesn't consider an wrapped Code entity is an inner error too. // So if you wanna to extract any inner error objects, use // errors.Unwrap for instead. The errors.Unwrap could extract all // of them one by one: // // var err = errors.New("hello").WithErrors(io.EOF, io.ShortBuffers) // var e error = err // for e != nil { // e = errors.Unwrap(err) // } // Causes() []error }
Error object
type Frame ¶
type Frame uintptr
Frame represents a program counter inside a Stack frame.
func (Frame) Format ¶
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 Stack ¶
type Stack []uintptr
Stack represents a Stack of program counters.
func (*Stack) Format ¶
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 WithStackInfo ¶
type WithStackInfo struct { *Stack // contains filtered or unexported fields }
WithStackInfo is exported now
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)
Attach _ Since v3.0.5, we break Attach() and remove its returning value. So WithStackInfo is a Container compliant type now.
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 an error object does not implement Cause interface, the original error object will be returned. If the error is nil, nil will be returned without further investigation.
func (*WithStackInfo) Causes ¶
func (w *WithStackInfo) Causes() []error
Causes simply returns the wrapped inner errors. It doesn't consider an wrapped Code entity is an inner error too. So if you wanna to extract any inner error objects, use errors.Unwrap for instead. The errors.Unwrap could extract all of them one by one:
var err = errors.New("hello").WithErrors(io.EOF, io.ShortBuffers) var e error = err for e != nil { e = errors.Unwrap(err) }
func (*WithStackInfo) Data ¶ added in v3.0.5
func (w *WithStackInfo) Data() []interface{}
Data returns the wrapped common user data by WithData. The error objects with passed WithData will be moved into inner errors set, so its are excluded from Data().
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) 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) IsEmpty ¶
func (w *WithStackInfo) IsEmpty() bool
IsEmpty tests has attached errors
func (*WithStackInfo) TaggedData ¶ added in v3.0.5
func (w *WithStackInfo) TaggedData() TaggedData
TaggedData returns the wrapped tagged user data by WithTaggedData.
func (*WithStackInfo) WithCause ¶
func (w *WithStackInfo) WithCause(cause error) Buildable
WithCause sets the underlying error manually if necessary.
func (*WithStackInfo) WithCode ¶
func (w *WithStackInfo) WithCode(code Code) Buildable
WithCode specifies an error code. An error code `Code` is a integer number with error interface supported.
func (*WithStackInfo) WithData ¶
func (w *WithStackInfo) WithData(errs ...interface{}) Buildable
WithData appends errs if the general object is a error object. It can be used in defer-recover block typically. For example:
defer func() { if e := recover(); e != nil { err = errors.New("[recovered] copyTo unsatisfied ([%v] %v -> [%v] %v), causes: %v", c.indirectType(from.Type()), from, c.indirectType(to.Type()), to, e). WithData(e) n := log.CalcStackFrames(1) // skip defer-recover frame at first log.Skip(n).Errorf("%v", err) // skip go-lib frames and defer-recover frame, back to the point throwing panic } }()
func (*WithStackInfo) WithErrors ¶
func (w *WithStackInfo) WithErrors(errs ...error) Buildable
WithErrors attaches the given errs as inner errors. WithErrors is like our old Attach(). It wraps the inner errors into underlying container and represents them all in a singular up-level error object. The wrapped inner errors can be retrieved with errors.Causes:
var err = errors.New("hello").WithErrors(io.EOF, io.ShortBuffers) var errs []error = errors.Causes(err)
Or, use As() to extract its:
var errs []error errors.As(err, &errs)
func (*WithStackInfo) WithMessage ¶
func (w *WithStackInfo) WithMessage(message string, args ...interface{}) Buildable
WithMessage formats the error message
func (*WithStackInfo) WithSkip ¶
func (w *WithStackInfo) WithSkip(skip int) Buildable
WithSkip specifies a special number of stack frames that will be ignored.
func (*WithStackInfo) WithTaggedData ¶
func (w *WithStackInfo) WithTaggedData(siteScenes TaggedData) Buildable
WithTaggedData appends errs if the general object is a error object