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 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 Builder
- type Code
- 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) *WithStackInfo
- func (w *WithStackInfo) Cause() error
- func (w *WithStackInfo) Causes() []error
- 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) TypeIs(target error) bool
- func (w *WithStackInfo) Unwrap() error
- func (w *WithStackInfo) WithCause(cause error) *WithStackInfo
- func (w *WithStackInfo) WithCode(code Code) *WithStackInfo
- func (w *WithStackInfo) WithData(errs ...interface{}) *WithStackInfo
- func (w *WithStackInfo) WithErrors(errs ...error) *WithStackInfo
- func (w *WithStackInfo) WithMessage(message string, args ...interface{}) *WithStackInfo
- func (w *WithStackInfo) WithSkip(skip int) *WithStackInfo
- func (w *WithStackInfo) WithTaggedData(siteScenes TaggedData) *WithStackInfo
Constants ¶
const ( // AppName const AppName = "errors" // Version const Version = "3.0.1" // VersionInt const VersionInt = 0x030001 )
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 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
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 // Attach inner errors for backward compatibility to v2 Attach(errs ...error) *WithStackInfo }
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 )
func (Code) New ¶
func (c Code) New(msg string, args ...interface{}) *WithStackInfo
New create a new *CodedErr object based an error code
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 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) *WithStackInfo
Attach _
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) 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) 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