Documentation
¶
Overview ¶
Package errors provides an enhanced error management library.
When dealing with unexpected or undesired behavior on any system (like issues and exceptions) the more information available, structured and otherwise, the better. Preserving error structure and context is particularly important since, in general, string comparisons on error messages are vulnerable to injection and can even cause security problems. On distributed systems is very useful, and often required, to preserve these details across service boundaries as well.
The main goals of this package are:
- Provide a simple, extensible and "familiar" implementation that can be easily used as a drop-in replacement for the standard "errors" package and popular 3rd party libraries.
- Preserve the entire structure of errors across the wire using pluggable codecs.
- Produce portable and PII-safe error reports. These reports can then be sent to any 3rd party service or webhook.
- Enable fast, reliable and secure determination of whether a particular cause is present (not relying on the presence of a substring in the error message).
- Being easily composable; by making it extensible with additional error annotations and supporting special behavior on custom error types.
This library is mainly inspired on the original https://github.com/cockroachdb/errors package, while adding some specific adjustments. For additional information about the original package refer to [PR-36987](https://github.com/cockroachdb/cockroach/pull/36987)
Index ¶
- func As(err error, target interface{}) bool
- func Cause(err error) error
- func Combine(err, other error) error
- func Errorf(format string, args ...interface{}) error
- func Is(src, target error) bool
- func IsAny(src error, target ...error) bool
- func New(e interface{}) error
- func Opaque(err error) error
- func Report(err error, cc Codec) ([]byte, error)
- func Unwrap(err error) error
- func WithStack(err error) error
- func WithStackAt(err error, at int) error
- func Wrap(e error, prefix string) error
- func Wrapf(err error, format string, args ...interface{}) error
- type Codec
- type Error
- func (e *Error) AddEvent(ev Event)
- func (e *Error) AddHint(hint string)
- func (e *Error) Cause() error
- func (e *Error) Error() string
- func (e *Error) Events() []Event
- func (e *Error) Format(s fmt.State, verb rune)
- func (e *Error) Hints() []string
- func (e *Error) PortableTrace() []StackFrame
- func (e *Error) SetTag(key string, value interface{})
- func (e *Error) StackTrace() []StackFrame
- func (e *Error) Stamp() int64
- func (e *Error) Tags() map[string]interface{}
- func (e *Error) Unwrap() error
- type Event
- type HasStack
- type Redactable
- type StackFrame
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func As ¶
As unwraps `err` sequentially looking for an error that can be assigned to `target`, which must be a pointer. If it succeeds, it performs the assignment and returns true. Otherwise, it returns false. `target` must be a pointer to an interface or to a type implementing the error interface.
func Cause ¶
Cause will recursively retrieve the topmost error which does not provide a cause, which is assumed to be the original failure condition.
func Combine ¶
Combine the error given as first argument with an annotation that carries the error given as second argument. The second error does not participate in cause analysis (Is, IsAny, ...) and is only revealed when reporting out the error.
Considerations:
- If `other` is nil, the first error is returned as-is.
- If `err` doesn't support adding additional details, it is returned as-is.
func Errorf ¶
Errorf returns a new root error (i.e., without a cause) instance which stacktrace will point to the line of code that called this function.
If the format specifier includes a `%w` verb with an error operand, the returned error will implement an Unwrap method returning the operand. It is invalid to include more than one `%w` verb or to supply it with an operand that does not implement the `error` interface. The `%w` verb is otherwise a synonym for `%v`.
func Is ¶
Is detects whether the error is equal to a given error. Errors are considered equal by this function if:
- Are both the same object
- If `src` provides a custom `Is(e error) bool` implementation it will be used and the result returned
- If `target` provides a custom `Is(e error) bool` implementation it will be used and the result returned
- Comparison is true between `target` and `src` cause
- Comparison is true between `src` and `target` cause
func IsAny ¶
IsAny detects whether the error is equal to any of the provided target errors. This method uses the same equality rules as `Is`.
func New ¶
func New(e interface{}) error
New returns a new root error (i.e., without a cause) instance from the given value. If the provided `e` value is:
- An `Error` instance created with this package it will be returned as-is.
- An `error` value, will be set as the root cause for the new error instance.
- Any other value, will be passed to fmt.Errorf("%v") and the resulting error value set as the root cause for the new error instance.
The stacktrace will point to the line of code that called this function.
func Opaque ¶
Opaque returns an error with the same formatting as `err` but that does not match `err` and cannot be unwrapped. This will essentially drop existing error context, useful when requiring a processing "barrier". This method returns a new root error (i.e., without a cause) instance.
func Report ¶
Report an error instance by generating a portable/transmissible representation of it using the provided codec.
func Unwrap ¶
Unwrap unpacks wrapped errors. If its argument's type has an `Unwrap` method, it calls the method once. Otherwise, it returns nil.
func WithStack ¶
WithStack returns a new root error (i.e., without a cause) instance which stacktrace will point to the line of code that called this function.
func WithStackAt ¶
WithStackAt returns a new root error (i.e., without a cause) instance which stacktrace will point to the line of code that called this function; minus number of stacks specified in `at`.
Types ¶
type Codec ¶
type Codec interface {
// Encodes an error instance and produce a report.
Marshal(err error) ([]byte, error)
// Decoded an error report and restore an error instance.
// If this operation fails for whatever reason `ok` should
// be `false`.
Unmarshal(src []byte) (ok bool, err error)
}
Codec implementations provide a pluggable way to manage error across service boundaries; for example when transmitting error messages through a network.
type Error ¶
type Error struct {
// contains filtered or unexported fields
}
Error is an error with an attached stacktrace. It can be used wherever the builtin error interface is expected.
func FromRecover ¶
func FromRecover(src interface{}) *Error
FromRecover is a utility function to facilitate obtaining a useful error instance from a panicked goroutine. To use it, simply pass the native `recover()` to it from within the panicking goroutine:
recovered := FromRecover(recover())
func ParsePanic ¶
ParsePanic allows you to get an error object from the output of a go program that panicked.
func (*Error) Cause ¶
Cause of the error. Obtained by traversing the entire error stack until an error with a `cause` value of 'nil'. Errors without cause are expected to be the root error of a failure condition.
func (*Error) Events ¶
Events associated to the error, if any. Events usually provide valuable information on when/how an exception occurred.
func (*Error) Format ¶
Format error values using the escape codes defined by fmt.Formatter. The following verbs are supported:
%s error message. Simply prints the basic error message as a
string representation.
%v basic format. Print the error including its stackframe formatted
as in the standard library `runtime/debug.Stack()`.
%+v extended format. Returns the stackframe formatted as in the
standard library `runtime/debug.Stack()` but replacing the values
for `GOPATH` and `GOROOT` on file paths. This makes the traces
more portable and avoid exposing (noisy) local system details.
func (*Error) Hints ¶
Hints provide additional context to an error in the form of meaningful text messages. If no hints are set on the error instance this method returns `nil`.
func (*Error) PortableTrace ¶
func (e *Error) PortableTrace() []StackFrame
PortableTrace returns the frames in the callers stack attempting to remove any paths specific to the local system, making the information a bit more readable and portable.
func (*Error) SetTag ¶
SetTag registers a specific key/value pair on the error instance; replacing any previously set values under the same key.
func (*Error) StackTrace ¶
func (e *Error) StackTrace() []StackFrame
StackTrace returns the frames in the callers stack.
type Event ¶
type Event struct {
// Kind can be used to group specific events into categories or groups.
Kind string `json:"kind,omitempty"`
// Short and concise description of the event.
Message string `json:"message,omitempty"`
// UNIX timestamp (in milliseconds).
Stamp int64 `json:"stamp,omitempty"`
// Additional data associated with an event.
Attributes map[string]interface{} `json:"attributes,omitempty"`
}
Event instances can be used to provided additional contextual information for an error.
type HasStack ¶
type HasStack interface {
StackTrace() []StackFrame
}
HasStack is implemented by error types that natively provide robust stack traces.
type Redactable ¶
type Redactable interface {
// Redact the sensitive details out of the message.
Redact() string
// Disclose the sensitive details included in the message. Use with care.
Disclose() string
}
Redactable represents a message that contains some form of private or sensitive information that should be redacted when used as an error or log message.
func SensitiveMessage ¶
func SensitiveMessage(format string, args ...interface{}) Redactable
SensitiveMessage returns a redactable message container. The `args` included can be redacted out of the message; specially useful when used as an error or log message. The returned message container can be specially formatted using the standard escape codes defined by `fmt.Formatter`. The following verbs are supported:
%s return the redacted version of the message. %v return the redacted version of the message. %+v return the full version of the message.
type StackFrame ¶
type StackFrame struct {
// The path to the file containing this ProgramCounter.
File string `json:"filename,omitempty"`
// The line number in that file.
LineNumber int `json:"line_number,omitempty"`
// The name of the function that contains this ProgramCounter.
Function string `json:"function,omitempty"`
// The package that contains this function.
Package string `json:"package,omitempty"`
// The line of code (from File and Line) of the original source,
// if available.
SourceLine string `json:"source_line,omitempty"`
// The underlying ProgramCounter.
ProgramCounter uintptr `json:"program_counter,omitempty"`
}
A StackFrame contains all necessary information about a specific line in a callstack.
func (StackFrame) Format ¶
func (sf StackFrame) Format(s fmt.State, verb rune)
Format error values using the escape codes defined by fmt.Formatter. The following verbs are supported:
%v see '%s'
%s basic format. Returns the stackframe formatted as in the
standard library `runtime/debug.Stack()`.
%+v extended format. Returns the stackframe formatted as in the
standard library `runtime/debug.Stack()` but replacing the values
for `GOPATH` and `GOROOT` on file paths. This makes the traces
more portable and avoid exposing (noisy) local system details.