Categorygithub.com/joomcode/errorx
modulepackage
1.2.0
Repository: https://github.com/joomcode/errorx.git
Documentation: pkg.go.dev

# README

Github Actions Build Status GoDoc Report Card gocover.io Mentioned in Awesome Go

Highlights

The errorx library provides error implementation and error-related utilities. Library features include (but are not limited to):

  • Stack traces
  • Composability of errors
  • Means to enhance error both with stack trace and with message
  • Robust type and trait checks

Introduction

Conventional approach towards errors in Go is quite limited.

The typical case implies an error being created at some point:

return errors.New("now this is unfortunate")

Then being passed along with a no-brainer:

if err != nil {
  return err
}

And, finally, handled by printing it to the log file:

log.Printf("Error: %s", err)

It doesn't take long to find out that quite often this is not enough. There's little fun in solving the issue when everything a developer is able to observe is a line in the log that looks like one of those:

Error: EOF

Error: unexpected '>' at the beginning of value

Error: wrong argument value

An errorx library makes an approach to create a toolset that would help remedy this issue with these considerations in mind:

  • No extra care should be required for an error to have all the necessary debug information; it is the opposite that may constitute a special case
  • There must be a way to distinguish one kind of error from another, as they may imply or require a different handling in user code
  • Errors must be composable, and patterns like if err == io.EOF defeat that purpose, so they should be avoided
  • Some context information may be added to the error along the way, and there must be a way to do so without altering the semantics of the error
  • It must be easy to create an error, add some context to it, check for it
  • A kind of error that requires a special treatment by the caller is a part of a public API; an excessive amount of such kinds is a code smell

As a result, the goal of the library is to provide a brief, expressive syntax for a conventional error handling and to discourage usage patterns that bring more harm than they're worth.

Error-related, negative codepath is typically less well tested, though of, and may confuse the reader more than its positive counterpart. Therefore, an error system could do well without too much of a flexibility and unpredictability.

errorx

With errorx, the pattern above looks like this:

return errorx.IllegalState.New("unfortunate")
if err != nil {
  return errorx.Decorate(err, "this could be so much better")
}
log.Printf("Error: %+v", err)

An error message will look something like this:

Error: this could be so much better, cause: common.illegal_state: unfortunate
 at main.culprit()
	main.go:21
 at main.innocent()
	main.go:16
 at main.main()
	main.go:11

Now we have some context to our little problem, as well as a full stack trace of the original cause - which is, in effect, all that you really need, most of the time. errorx.Decorate is handy to add some info which a stack trace does not already hold: an id of the relevant entity, a portion of the failed request, etc. In all other cases, the good old if err != nil {return err} still works for you.

And this, frankly, may be quite enough. With a set of standard error types provided with errorx and a syntax to create your own (note that a name of the type is a good way to express its semantics), the best way to deal with errors is in an opaque manner: create them, add information and log as some point. Whenever this is sufficient, don't go any further. The simpler, the better.

Error check

If an error requires special treatment, it may be done like this:

// MyError = MyErrors.NewType("my_error")
if errorx.IsOfType(err, MyError) {
  // handle
}

Note that it is never a good idea to inspect a message of an error. Type check, on the other hand, is sometimes OK, especially if this technique is used inside of a package rather than forced upon API users.

An alternative is a mechanisms called traits:

// the first parameter is a name of new error type, the second is a reference to existing trait
TimeoutElapsed       = MyErrors.NewType("timeout", errorx.Timeout())

Here, TimeoutElapsed error type is created with a Timeout() trait, and errors may be checked against it:

if errorx.HasTrait(err, errorx.Timeout()) {
  // handle
}

Note that here a check is made against a trait, not a type, so any type with the same trait would pass it. Type check is more restricted this way and creates tighter dependency if used outside of an originating package. It allows for some little flexibility, though: via a subtype feature a broader type check can be made.

Wrap

The example above introduced errorx.Decorate(), a syntax used to add message as an error is passed along. This mechanism is highly non-intrusive: any properties an original error possessed, a result of a Decorate() will possess, too.

Sometimes, though, it is not the desired effect. A possibility to make a type check is a double edged one, and should be restricted as often as it is allowed. The bad way to do so would be to create a new error and to pass an Error() output as a message. Among other possible issues, this would either lose or duplicate the stack trace information.

A better alternative is:

return MyError.Wrap(err, "fail")

With Wrap(), an original error is fully retained for the log, but hidden from type checks by the caller.

See WrapMany() and DecorateMany() for more sophisticated cases.

Stack traces

As an essential part of debug information, stack traces are included in all errorx errors by default.

When an error is passed along, the original stack trace is simply retained, as this typically takes place along the lines of the same frames that were originally captured. When an error is received from another goroutine, use this to add frames that would otherwise be missing:

return errorx.EnhanceStackTrace(<-errorChan, "task failed")

Result would look like this:

Error: task failed, cause: common.illegal_state: unfortunate
 at main.proxy()
	main.go:17
 at main.main()
	main.go:11
 ----------------------------------
 at main.culprit()
	main.go:26
 at main.innocent()
	main.go:21

On the other hand, some errors do not require a stack trace. Some may be used as a control flow mark, other are known to be benign. Stack trace could be omitted by not using the %+v formatting, but the better alternative is to modify the error type:

ErrInvalidToken    = AuthErrors.NewType("invalid_token").ApplyModifiers(errorx.TypeModifierOmitStackTrace)

This way, a receiver of an error always treats it the same way, and it is the producer who modifies the behaviour. Following, again, the principle of opacity.

Other relevant tools include EnsureStackTrace(err) to provide an error of unknown nature with a stack trace, if it lacks one.

Stack traces benchmark

As performance is obviously an issue, some measurements are in order. The benchmark is provided with the library. In all of benchmark cases, a very simple code is called that does nothing but grows a number of frames and immediately returns an error.

Result sample, MacBook Pro Intel Core i7-6920HQ CPU @ 2.90GHz 4 core:

namerunsns/opnote
BenchmarkSimpleError102000000057.2simple error, 10 frames deep
BenchmarkErrorxError1010000000138same with errorx error
BenchmarkStackTraceErrorxError1010000001601same with collected stack trace
BenchmarkSimpleError1003000000421simple error, 100 frames deep
BenchmarkErrorxError1003000000507same with errorx error
BenchmarkStackTraceErrorxError1003000004450same with collected stack trace
BenchmarkStackTraceNaiveError100-82000588135same with naive debug.Stack() error implementation
BenchmarkSimpleErrorPrint1002000000617simple error, 100 frames deep, format output
BenchmarkErrorxErrorPrint1002000000935same with errorx error
BenchmarkStackTraceErrorxErrorPrint1003000058965same with collected stack trace
BenchmarkStackTraceNaiveErrorPrint100-82000599155same with naive debug.Stack() error implementation

Key takeaways:

  • With deep enough call stack, trace capture brings 10x slowdown
  • This is an absolute worst case measurement, no-op function; in a real life, much more time is spent doing actual work
  • Then again, in real life code invocation does not always result in error, so the overhead is proportional to the % of error returns
  • Still, it pays to omit stack trace collection when it would be of no use
  • It is actually much more expensive to format an error with a stack trace than to create it, roughly another 10x
  • Compared to the most naive approach to stack trace collection, error creation it is 100x cheaper with errorx
  • Therefore, it is totally OK to create an error with a stack trace that would then be handled and not printed to log
  • Realistically, stack trace overhead is only painful either if a code is very hot (called a lot and returns errors often) or if an error is used as a control flow mechanism and does not constitute an actual problem; in both cases, stack trace should be omitted

More

See godoc for other errorx features:

  • Namespaces
  • Type switches
  • errorx.Ignore
  • Trait inheritance
  • Dynamic properties
  • Panic-related utils
  • Type registry
  • etc.

# Packages

# Functions

CaseNoError is a synthetic trait used in TraitSwitch, signifying an absence of error.
CaseNoTrait is a synthetic trait used in TraitSwitch, signifying a presence of non-nil error that lacks specified traits.
Cast attempts to cast an error to errorx Type, returns nil if cast has failed.
Decorate allows to pass some text info along with a message, leaving its semantics totally intact.
DecorateMany performs a transparent wrap of multiple errors with additional message.
Duplicate is a trait that marks such an error where an update is failed as a duplicate.
EnhanceStackTrace has all the properties of the Decorate() method and additionally extends the stack trace of the original error.
EnsureStackTrace is a utility to ensure the stack trace is captured in provided error.
ErrorFromPanic recovers the original error from panic, best employed along with Panic() function from the same package.
ExtractContext is a statically typed helper to extract a context property from an error.
ExtractPayload is a helper to extract a payload property from an error.
ExtractProperty attempts to extract a property value by a provided key.
GetTypeName returns the full type name if an error; returns an empty string for non-errorx error.
HasTrait checks if an error possesses the expected trait.
Ignore returns nil if an error is of one of the provided types, returns the provided error otherwise.
IgnoreWithTrait returns nil if an error has one of the provided traits, returns the provided error otherwise.
InitializeStackTraceTransformer provides a transformer to be used in formatting of all the errors.
IsDuplicate checks for Duplicate trait.
IsNotFound checks for NotFound trait.
IsOfType is a type check for errors.
IsTemporary checks for Temporary trait.
IsTimeout checks for Timeout trait.
NewErrorBuilder creates error builder from an existing error type.
NewNamespace defines a namespace with a name and, optionally, a number of inheritable traits.
NewType defines a new distinct type within a namespace.
NotFound is a trait that marks such an error where the requested object is not found.
NotRecognisedType is a synthetic type used in TypeSwitch, signifying a presence of non-nil error of some other type.
Panic is an alternative to the built-in panic call.
PropertyContext is a context property, value is expected to be of context.Context type.
PropertyPayload is a payload property, value may contain user defined structure with arbitrary data passed along with an error.
RegisterPrintableProperty registers a new property key for informational value.
RegisterProperty registers a new property key.
RegisterTrait declares a new distinct traits.
RegisterTypeSubscriber adds a new TypeSubscriber.
ReplicateError is a utility function to duplicate error N times.
Temporary is a trait that signifies that an error is temporary in nature.
Timeout is a trait that signifies that an error is some sort iof timeout.
TraitSwitch is used to perform a switch around the trait of an error.
TypeSwitch is used to perform a switch around the type of an error.
WithContext is a statically typed helper to add a context property to an error.
WithPayload is a helper to add a payload property to an error.
WrapMany is a utility to wrap multiple errors.

# Constants

TypeModifierOmitStackTrace is a type modifier; an error type with such modifier omits the stack trace collection upon creation of an error instance.
TypeModifierTransparent is a type modifier; an error type with such modifier creates transparent wrappers by default.

# Variables

AssertionFailed is a type for assertion error.
CommonErrors is a namespace for general purpose errors designed for universal use.
ConcurrentUpdate is a type for concurrent update error.
DataUnavailable is a type for unavailable data error.
ExternalError is a type for external error.
IllegalArgument is a type for invalid argument error.
IllegalFormat is a type for invalid format error.
IllegalState is a type for invalid state error.
InitializationFailed is a type for initialization error.
InternalError is a type for internal error.
Interrupted is a type for interruption error.
NotImplemented is an error type for lacking implementation.
RejectedOperation is a type for rejected operation error.
TimeoutElapsed is a type for timeout error.
UnsupportedOperation is a type for unsupported operation error.
UnsupportedVersion is a type for unsupported version error.

# Structs

Error is an instance of error object.
ErrorBuilder is a utility to compose an error from type.
Namespace is a way go group a number of error types together, and each error type belongs to exactly one namespace.
NamespaceKey is a comparable descriptor of a Namespace.
Property is a key to a dynamic property of an error.
Trait is a static characteristic of an error type.
Type is a distinct error type.

# Interfaces

TypeSubscriber is an interface to receive callbacks on the registered error namespaces and types.

# Type aliases

StackTraceFilePathTransformer is a used defined transformer for file path in stack trace output.
TypeModifier is a way to change a default behaviour for an error type, directly or via type hierarchy.