{"modulePath":"github.com/corestoreio/errors","version":"v3.1.1+incompatible","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package errors\n\nPackage errors provides simple error handling primitives and behavioral errors.\n\nHello there! Read the presentation [http://dave.cheney.net/paste/gocon-spring-2016.pdf](http://dave.cheney.net/paste/gocon-spring-2016.pdf) to see what the big deal is.\n\n[http://dave.cheney.net/2016/04/27/dont-just-check-errors-handle-them-gracefully](http://dave.cheney.net/2016/04/27/dont-just-check-errors-handle-them-gracefully)\n\nRead this for asserting errors for their behaviour [http://dave.cheney.net/2014/12/24/inspecting-errors](http://dave.cheney.net/2014/12/24/inspecting-errors)\n\nThe traditional error handling idiom in Go is roughly akin to\n\n\tif err != nil {\n\t        return err\n\t}\n\nwhich applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error.\n\n### Adding context to an error {#hdr-Adding_context_to_an_error}\n\nThe errors.Wrap function returns a new error that adds context to the original error by recording a stack trace at the point Wrap is called, and the supplied message. For example\n\n\t_, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t        return errors.Wrap(err, \"read failed\")\n\t}\n\nIf additional control is required the errors.WithStack and errors.WithMessage functions destructure errors.Wrap into its component operations of annotating an error with a stack trace and an a message, respectively.\n\n### Retrieving the cause of an error {#hdr-Retrieving_the_cause_of_an_error}\n\nUsing errors.Wrap constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface\n\n\ttype causer interface {\n\t        Cause() error\n\t}\n\ncan be inspected by errors.Cause. errors.Cause will recursively retrieve the topmost error which does not implement causer, which is assumed to be the original cause. For example:\n\n\tswitch err := errors.Cause(err).(type) {\n\tcase *MyError:\n\t        // handle specifically\n\tdefault:\n\t        // unknown error\n\t}\n\ncauser interface is not exported by this package, but is considered a part of stable public API.\n\n### Formatted printing of errors {#hdr-Formatted_printing_of_errors}\n\nAll error values returned from this package implement fmt.Formatter and can be formatted by the fmt package. The following verbs are supported\n\n\t%s    print the error. If the error has a Cause it will be\n\t      printed recursively\n\t%v    see %s\n\t%+v   extended format. Each Frame of the error's StackTrace will\n\t      be printed in detail.\n\n### Retrieving the stack trace of an error or wrapper {#hdr-Retrieving_the_stack_trace_of_an_error_or_wrapper}\n\nNew, Errorf, Wrap, and Wrapf record a stack trace at the point they are invoked. This information can be retrieved with the following interface.\n\n\ttype stackTracer interface {\n\t        StackTrace() errors.StackTrace\n\t}\n\nWhere errors.StackTrace is defined as\n\n\ttype StackTrace []Frame\n\nThe Frame type represents a call site in the stack trace. Frame supports the fmt.Formatter interface that can be used for printing information about the stack trace of this error. For example:\n\n\tif err, ok := err.(stackTracer); ok {\n\t        for _, f := range err.StackTrace() {\n\t                fmt.Printf(\"%+s:%d\", f)\n\t        }\n\t}\n\nstackTracer interface is not exported by this package, but is considered a part of stable public API.\n\nSee the documentation for Frame.Format for more details.\n\n## Constants\n\n```go\nconst KindSeparator = \"|\"\n```\nKindSeparator separates multiple Kinds packed into one Kind.\n\n## Functions\n\n```go\nfunc Attach(err error, k Kind) error\n```\nAttach adds Kind \\`k\\` to an error but only if the error has been created with this package. For example you can create a Restricted error and then attach a Temporary kind. Now the error has two kinds. If the error hasn't been created by this package, then nothing happens.\n\n```go\nfunc Cause(err error) error\n```\nCause returns the underlying cause of the error, if possible. An error value has a cause if it implements the following interface:\n\n\ttype causer interface {\n\t       Cause() error\n\t}\n\nIf the error does not implement Cause, the original error will be returned. If the error is nil, nil will be returned without further investigation.\n\n```go\nfunc CausedBehaviour(err error, k Kind) bool\n```\nCausedBehaviour returns the first underlying caused kind/behaviour of the error, if possible. An error value has a cause if it implements the following interface:\n\n\ttype Causer interface {\n\t       Cause() error\n\t}\n\nIf the error does not implement Cause or is nil, false will be returned. The variable \\`k\\` gets called on each unwrapped \"cause\" error.\n\n```go\nfunc Detach(err error, k Kind) error\n```\nDetach opposite of Attach.\n\n```go\nfunc Errorf(format string, args ...interface{}) error\n```\nErrorf formats according to a format specifier and returns the string as a value that satisfies error. Errorf also records the stack trace at the point it was called.\n\n```go\nfunc Is(err error, k Kind) bool\n```\nIs returns true if \\`err\\` is of Kind \\`k\\`. It unwraps all underlying errors which implement the Causer interface. Does not supported implemented behaviour functions.\n\n```go\nfunc MarshalAppend(err error, b []byte) []byte\n```\nMarshalAppend marshals an arbitrary error into a byte slice. The result is appended to b, which may be nil. It returns the argument slice unchanged if the error is nil. If the error is not an \\*Error, it just records the result of err.Error(). Otherwise it encodes the full Error struct.\n\n```go\nfunc MatchAll(err error, k ...Kind) bool\n```\nMatchAll checks if all Kinds are included in \\`err\\`. It does not unwrap \\`err\\` by its \\`Causer\\` interface. Does not supported implemented behaviour functions.\n\n```go\nfunc MatchAny(err error, k ...Kind) bool\n```\nMatchAny checks if at least one Kind is included in \\`err\\`. It does not unwrap \\`err\\` by its \\`Causer\\` interface. Does not supported implemented behaviour functions.\n\n```go\nfunc New(message string) error\n```\nNew returns an error with the supplied message. New also records the stack trace at the point it was called.\n\n```go\nfunc Unmarshal(b []byte) error\n```\nUnmarshal unmarshals the byte slice into an error value. If the slice is nil or empty, it returns nil. Otherwise the byte slice must have been created by \\`Marshal\\` or \\`MarshalAppend\\`. If the encoded error was of type \\`errors\\` within this package, the returned error value will have that underlying type. Otherwise it will be just a simple value that implements the error interface.\n\n```go\nfunc UnwrapStack(err error) []byte\n```\nUnwrapStack tries to extract the previous stack trace after unmarshalling a byte slice into an error. It can return nil.\n\n```go\nfunc WithMessage(err error, message string) error\n```\nWithMessage annotates err with a new message. If err is nil, WithMessage returns nil.\n\n```go\nfunc WithStack(err error) error\n```\nWithStack annotates err with a stack trace at the point WithStack was called. If err is nil, WithStack returns nil.\n\n```go\nfunc Wrap(err error, message string) error\n```\nWrap 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.\n\n```go\nfunc Wrapf(err error, format string, args ...interface{}) error\n```\nWrapf returns an error annotating err with a stack trace at the point Wrapf is call, and the format specifier. If err is nil, Wrapf returns nil.\n\n## Types\n\n```go\ntype Frame uintptr\n```\nFrame represents a program counter inside a stack frame. For historical reasons if Frame is interpreted as a uintptr its value represents the program counter + 1.\n\n```go\nfunc (f Frame) Format(s fmt.State, verb rune)\n```\nFormat formats the frame according to the fmt.Formatter interface.\n\n\t%s    source file\n\t%d    source line\n\t%n    function name\n\t%v    equivalent to %s:%d\n\nFormat accepts flags that alter the printing of some verbs, as follows:\n\n\t%+s   function name and path of source file relative to the compile time\n\t      GOPATH separated by \\n\\t (\u003cfuncname\u003e\\n\\t\u003cpath\u003e)\n\t%+v   equivalent to %+s:%d\n\n```go\nfunc (f Frame) MarshalText() ([]byte, error)\n```\nMarshalText formats a stacktrace Frame as a text string. The output is the same as that of fmt.Sprintf(\"%+v\", f), but without newlines or tabs.\n\n```go\ntype Kind string\n```\nKind defines the kind or behaviour of an error. An error can have multiple Kinds wrapped into each other via bit operations. A zero Kind represents an empty Kind. The underlying type uint might change, so please use the functions provided in this package to manipulate the Kind. 63 different constants are currently supported.\n\n```go\nconst (\n\tAborted            Kind = \"Aborted\"\n\tAlreadyCaptured    Kind = \"AlreadyCaptured\"\n\tAlreadyClosed      Kind = \"AlreadyClosed\"\n\tAlreadyExists      Kind = \"AlreadyExists\"\n\tAlreadyInUse       Kind = \"AlreadyInUse\"\n\tAlreadyRefunded    Kind = \"AlreadyRefunded\"\n\tBadEncoding        Kind = \"BadEncoding\"\n\tBlocked            Kind = \"Blocked\"\n\tConnectionFailed   Kind = \"ConnectionFailed\"\n\tConnectionLost     Kind = \"ConnectionLost\"\n\tCorruptData        Kind = \"CorruptData\"\n\tDeclined           Kind = \"Declined\"\n\tDecryptionFailed   Kind = \"DecryptionFailed\"\n\tDenied             Kind = \"Denied\"\n\tDuplicated         Kind = \"Duplicated\"\n\tEmpty              Kind = \"Empty\"\n\tEncryptionFailed   Kind = \"EncryptionFailed\"\n\tExceeded           Kind = \"Exceeded\"\n\tExists             Kind = \"Exists\"\n\tExpired            Kind = \"Expired\"\n\tFatal              Kind = \"Fatal\"\n\tInProgress         Kind = \"InProgress\"\n\tInsufficient       Kind = \"Insufficient\"\n\tInterrupted        Kind = \"Interrupted\"\n\tIsDirectory        Kind = \"IsDirectory\"\n\tIsFile             Kind = \"IsFile\"\n\tLocked             Kind = \"Locked\"\n\tMismatch           Kind = \"Mismatch\"\n\tNotAcceptable      Kind = \"NotAcceptable\"\n\tNotAllowed         Kind = \"NotAllowed\"\n\tNotDirectory       Kind = \"NotDirectory\"\n\tNotEmpty           Kind = \"NotEmpty\"\n\tNotExists          Kind = \"NotExists\"\n\tNotFile            Kind = \"NotFile\"\n\tNotFound           Kind = \"NotFound\"\n\tNotImplemented     Kind = \"NotImplemented\"\n\tNotRecoverable     Kind = \"NotRecoverable\"\n\tNotSupported       Kind = \"NotSupported\"\n\tNotValid           Kind = \"NotValid\"\n\tOutOfDate          Kind = \"OutOfDate\"\n\tOutOfRange         Kind = \"OutOfRange\"\n\tOverflowed         Kind = \"Overflowed\"\n\tPermissionDenied   Kind = \"PermissionDenied\"\n\tQuotaExceeded      Kind = \"QuotaExceeded\"\n\tReadFailed         Kind = \"ReadFailed\"\n\tRejected           Kind = \"Rejected\"\n\tRequired           Kind = \"Required\"\n\tRestricted         Kind = \"Restricted\"\n\tRevoked            Kind = \"Revoked\"\n\tTemporary          Kind = \"Temporary\"\n\tTerminated         Kind = \"Terminated\"\n\tTimeout            Kind = \"Timeout\"\n\tTooLarge           Kind = \"TooLarge\"\n\tTooShort           Kind = \"TooShort\"\n\tUnauthorized       Kind = \"Unauthorized\"\n\tUnavailable        Kind = \"Unavailable\"\n\tUserNotFound       Kind = \"UserNotFound\"\n\tVerificationFailed Kind = \"VerificationFailed\"\n\tWriteFailed        Kind = \"WriteFailed\"\n\tWrongVersion       Kind = \"WrongVersion\"\n)\n```\nThese constants define different behaviours. They are not sorted and new constants must be appended at the end. The zero kind defines empty.\n\n```go\nconst NoKind Kind = \"\"\n```\nNoKind defines an empty Kind with no behaviour. This constant must be placed outside the constant block to avoid a conflict with iota.\n\n```go\nfunc UnwrapKind(err error) (k Kind)\n```\nUnwrapKind extract the Kind of an error. If the error has not been created via this package or does not implement interface \\`Kinder\\`, this function will return zero.\n\n```go\nfunc (k Kind) Empty() bool\n```\nEmpty returns true if no behaviour/kind has been set.\n\n```go\nfunc (k Kind) Error() string\n```\nError implements error interface and returns the string without any formatting or stack trace. It calls under the hood the string function.\n\n```go\nfunc (k Kind) Match(err error) bool\n```\nMatch returns true if \\`err\\` matches the Kind. Very fast matching.\n\n```go\nfunc (k Kind) MatchInterface(err error) bool\n```\nMatchInterface supports interface behaviour type matching to test for a kind. This allows a package to define a behaviour/kind of an error without importing this package. An error type should implement a function like:\n\n\tinterface{ Fatal() bool }\n\nWhere \\`Fatal\\` can be any behaviour name like the constants in this package. MatchInterface is 40x slower than function \\`Match\\`.\n\n```go\nfunc (k Kind) New(err error, msg string, args ...interface{}) error\n```\nNew wraps err with the specified Kind. Allows to write an additional message which gets formatted by fmt.Sprintf. It attaches a stack trace.\n\n```go\nfunc (k Kind) Newf(format string, args ...interface{}) error\n```\nNewf creates a new error with a message formatted by fmt.Sprintf and a stack trace.\n\n```go\nfunc (k Kind) String() string\n```\nString returns the underlying string.\n\n```go\nfunc (k Kind) Unwrap() Kinds\n```\nUnwrap returns all Kind where the bit flag is set. If Kind is empty, returns nil.\n\n```go\ntype Kinder interface {\n\tErrorKind() Kind\n}\n```\nKinder may be implemented by any other custom error type to define desired kinds/behaviours. Multiple Kinds can be returned.\n\n```go\ntype Kinds []Kind\n```\nKinds a slice of Kind. Each Kind does not contain any other Kind.\n\n```go\nfunc UnwrapKinds(err error) Kinds\n```\nUnwrapKinds checks if error has a Kind/behaviour and returns a slice with all found Kinds. The returned slice is sorted numerical.\n\n```go\nfunc (ks Kinds) String() string\n```\nString creates a comma separated list of the Kind names.\n\n```go\ntype StackTrace []Frame\n```\nStackTrace is stack of Frames from innermost (newest) to outermost (oldest).\n\n```go\nfunc (st StackTrace) Format(s fmt.State, verb rune)\n```\nFormat formats the stack of Frames according to the fmt.Formatter interface.\n\n\t%s\tlists source files for each Frame in the stack\n\t%v\tlists the source file and line number for each Frame in the stack\n\nFormat accepts flags that alter the printing of some verbs, as follows:\n\n\t%+v   Prints filename, function, and line number for each Frame in the stack.\n\n","path":"github.com/corestoreio/errors","name":"errors","synopsis":"Package errors provides simple error handling primitives and behavioral errors.","isRedistributable":true}
