wrappederror

package module
v1.0.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 8, 2021 License: MIT Imports: 12 Imported by: 0

README ยถ

Package ๐ŸŽ'derror

Go Tests Go Coverage Go Reference

Package wrappederror implements an error type in Go for wrapping errors.

It contains handy methods to examine the error chain, stack and your source, and it plays nicely with other error types.

Installing

Navigate to your module and execute the following.

$ go get github.com/colinc86/wrappederror

Import the package:

import we "github.com/colinc86/wrappederror"

๐ŸŽ Wrapping Errors

Use the package's New function to wrap errors and give them context.

// Get an error
err := errors.New("some error")

// Wrap the error with some context
e := we.New(err, "oh no")

// Print the wrapped error
fmt.Println(e)
oh no: some error

An error's context doesn't have to be a string.

myObj := &MyObj{}
if data, err := json.Marshal(myObj); err != nil {
  // If we failed to marshal myObj, then attach it to the error for context
  return we.New(err, myObj)
}

๐Ÿ” Examining Errors

There are many ways to examine an error...

๐Ÿ–‡ Error and Context

The error's Error method returns an inline string representation of the entire error chain with each component separated by the characters : (colon, space).

// Print the entire error chain
fmt.Println(e2.Error())
error C: error B: error A

To only examine the receiver's context, use the Context method.

// Only print the error's context
fmt.Printf("%+v", e2.Context())
error C
๐Ÿ“ Depth

Errors have depth. That is, the number of errors, not including itself, in the error chain.

For eample, the following prints the depth of each error in the chain.

// Create some errors
e0 := we.New(nil, "error A")
e1 := we.New(e0, "error B")
e2 := we.New(e1, "error C")

// Print their depths
fmt.Printf("e0 depth: %d\n", e0.Depth())
fmt.Printf("e1 depth: %d\n", e1.Depth())
fmt.Printf("e2 depth: %d\n", e2.Depth())
e0 depth: 0
e1 depth: 1
e2 depth: 2
๐Ÿ”— Chain

Access the error chain as a flattened slice instead of wrapped errors using the Chain method.

// Store the slice [e2, e1, e0] in c
c := e2.Chain()

Optionally, directly access an error with a given depth or index.

// Get the last error in the chain
errA := e2.ErrorWithDepth(0)

// Get the first error in the chain
errB := e2.ErrorWithIndex(0)

// Gets nil
errC := e2.ErrorWithDepth(3)
errD := e2.ErrorWithIndex(-1)
๐Ÿ‘ฃ Walk

Step through the error chain with the Walk method. Walk calls the step function for every error in the chain until either the last error unwraps to nil, or the step function returns false.

e2.Walk(func (err error) bool {
  // Do something with the error

  if err == ErrSomeParticularType {
    // Don't continue with the walk
    return false
  }

  if errors.Unwrap(err) == nil {
    // This is the last error in the chain...
    // Do something else
  }

  // Continue with the walk
  return true
})
๐Ÿ—บ Trace

Get an error trace by calling the Trace method. This method returns a prettified string representation of the error chain with caller information. Errors in the chain not defined by this package log their depth and result of calling Error.

// Print an error trace
fmt.Println(e2.Trace())
โ”Œ 2: main.function (main.go:61) error C
โ”œ 1: main.function (main.go:60) error B
โ”” 0: main.function (main.go:59) error A
๐Ÿ—‚ Metadata

Errors come attached with metadata. Metadata types contain information about the error that can be useful when debugging such as

  • the error's index during the process's execution created by this package,
  • the number of similar non-nil errors that have been wrapped,
  • the duration since the process was launched and when the error was created,
  • and the time that the error was created.
// Print the error's metadata
fmt.Println(e.Metadata)
(#1) (โ‰ˆ0) (+10.000280) 2021-03-07 13:29:07.179446 -0600 CST m=+10.000589560

The package keeps track of the number of similar errors by keeping a hash map of the errors that have been wrapped. It creates a 128-bit hash of an error's Error method and keeps a count of the number of identical hashes. You can turn this behavior on/off by using the SetTrackSimilarErrors configuration method.

๐Ÿ“‡ Caller

Errors capture call information accessible through the Caller property. Examine information such as code metadata, a stack trace and source fragment.

๐Ÿ“„ File, Function and Line
// Print call information
fmt.Println(e2.Caller)
main.function (main.go:19)
๐Ÿงฌ Stack Trace

Along with basic file, function and line information, you can use the caller to provide a stack trace of the goroutine the error was created on.

// Print a stack trace
fmt.Println(e.Caller.StackTrace)
goroutine 18 [running]:
runtime/debug.Stack(0x0, 0x0, 0x0)
  /usr/local/Cellar/go/1.16/libexec/src/runtime/debug/stack.go:24 +0xa5
github.com/colinc86/wrappederror.currentCaller(0x1, 0x0)
  /Users/colin/Documents/Programming/Go/wrappederror/caller.go:65 +0x45
github.com/colinc86/wrappederror.TestStack(0xc000082600)
  /Users/colin/Documents/Programming/Go/wrappederror/caller_test.go:25 +0x3f
testing.tRunner(0xc000082600, 0x11acff0)
  /usr/local/Cellar/go/1.16/libexec/src/testing/testing.go:1194 +0x1a3
created by testing.(*T).Run
  /usr/local/Cellar/go/1.16/libexec/src/testing/testing.go:1239 +0x63c
๐Ÿงฉ Source Fragments

When possible, the caller type also captures source code information.

// Print the source code around the line that the error was created on
fmt.Println(e2.Caller.SourceFragment)
[47-51] /Users/colin/Documents/Programming/Go/wrappederror/wcaller_test.go

func TestCallerSource(t *testing.T) {
	c := currentCaller(1)
	if c.Source() == "" {
		t.Error("Expected a source trace.")

The caller collects the immediate two lines above to two lines below the calling line. If you want more or less information you can set (and check) the radius with the SetSourceFragmentRadius and SourceFragmentRadius functions. You can also turn the feature off altogether with SetCollectSourceFragments.

// If the radius hasn't been set to 5...
if we.Config().SourceFragmentRadius() != 5 {
  // Set the radius to 5
  we.Config().SetSourceFragmentRadius(5)
}
๐Ÿ”ฌ Process

Use the error's Process property to get information about the current process at the time the error was created.

๐Ÿ’ป Goroutines, CPUs and CGO

Process types contain some general process information like the number of current goroutines, the number of available CPUs, and the number of cgo functions executed.

// Print the process information when the error was created
fmt.Println(e.Process)
goroutines: 2, cpus: 16, cgos: 0
๐Ÿ“Š Memory Statistics

Memory statistics are available with the e.Process.Memory property.

// Print the allocated memory at the time of the error
fmt.Printf("Allocated memory at %s: %d bytes\n", e.Metadata.Time, e.Process.Memory.Alloc)
๐Ÿ“Œ Debugging

It is also possible to trigger a breakpoint programatically when an error is received using the Process type.

// doSomething returns a wrapped error
if e := doSomething(); e != nil {
  // Initiate a breakpoint
  e.Process.Break()

  // Continue
  return we
}

All calls to Process.Break() are ignored by default. A call to the configuration's SetIgnoreBreakpoints with a value of false must happen before Process types will attempt to break.

// Ignore all breakpoints if we aren't debugging
we.Config().SetIgnoreBreakpoints(os.Getenv("DEBUG") != "true")

e := New(nil, err)

// Only attempts to break if the env var DEBUG is "true"
e.Break()

๐Ÿšจ Severity Detection

The package can detect the severity of newly wrapped errors using a table of registered ErrorSeverity types. The package matches the severity's regular expression against the output of each error's Error method in the error chain. A score in the interval [0.0, 1.0] is calculated by calculating the ratio of the number of matched characters in the string to the total number of characters in the string.

To register a new error severity, first create a new instance of the structure such that no error is returned.

// Create two error severities
s1, err := we.NewErrorSeverity("Network Timeout", "i/o timeout", we.ErrorSeverityLevelModerate)
if err != nil {
  fmt.Printf("Invalid regex: %s\n", err)
}

s2, err := we.NewErrorSeverity("๐Ÿšจ", "fail", we.ErrorSeverityLevelHigh)
if err != nil {
  fmt.Printf("Invalid regex: %s\n", err)
}

and then register the error severity with the package.

if err := we.RegisterErrorSeverity(s1); err != nil {
  fmt.Printf("Unable to register error severity: %s\n", err)
}

if err := we.RegisterErrorSeverity(s2); err != nil {
  fmt.Printf("Unable to register error severity: %s\n", err)
}

Now, when new errors are created, they will be matched against the registered error severities and the error's Metadata.Severity may contain a non-nil value.

// Got a network timeout
e1 := errors.New("dial tcp 0.0.0.0:3000: i/o timeout")
e2 := New(e1, "get request failed")
if e2.Metadata.Severity != nil {
  fmt.Println(e2.Metadata.Severity)
}

// Got an error saving a file
e3 := errors.New("save failed because file does not exist")
e4 := New(e3, "unable to save file")
e5 := New(e4, "file error")
if e5.Metadata.Severity != nil {
  fmt.Println(e5.Metadata.Severity)
}
[moderate] Network Timeout
[high] ๐Ÿšจ

To unregister error severities, call the UnregisterErrorSeverity function with the severity you want to unregister.

we.UnregisterErrorSeverity(s1)
we.UnregisterErrorSeverity(s2)

The available ErrorSeverityLevel constants are

Level
ErrorSeverityLevelNone
ErrorSeverityLevelLow
ErrorSeverityLevelModerate
ErrorSeverityLevelHigh
ErrorSeverityLevelSevere

๐Ÿงฑ Marshaling Errors

The package supports marshaling errors into JSON, but because the error type defined in this package wraps errors of type error, a bijective UnmarshalJSON method isn't possible. Intead of attempting to guess at wrapped types, the package just doesn't try.

The types Caller, Process, Metadata and ErrorSeverity do implement both JSON marshaling and unmarshaling.

The error chain can get long, and if errors are collecting caller and process information, then JSON objects for a "single" top-level error may be disproportionately large compared to the rest of the JSON object they're embedded in. The package provides a method for determining how errors are marshaled in to JSON data.

// Marshal full JSON objects
we.Config().SetMarshalMinimalJSON(false)

// Marshal a slimmed-down version of errors
we.Config().SetMarshalMinimalJSON(true)

The package marshals its error type in to one of two versions of JSON (defined by the MarshalMinimalJSON configuration value):

// The "full" version of an error
{
  "context": "the error's context",
  "depth": 0,
  "wraps": { /* another error or null */ },
  "caller": {
    "file": "/path/to/file",
    "function": "function",
    "line": 0,
    "stackTrace": "trace",
    "sourceFragment:" "source"
  },
  "process": {
    "goroutines": 1,
    "cpus": 8,
    "cgos": 0,
    "memory": { /* runtime.MemStats */ },
  },
  "metadata": {
    "time": "the time",
    "duration": 0.0,
    "index": 0,
    "similar": 0
  }
}
// The "minimal" version of an error
{
  "context": "the error's context",
  "depth": 0,
  "wraps": { /* another error or null */ },
  "time": "the time",
  "duration": 0.0,
  "index": 0,
  "similar": 0,
  "file": "/path/to/file",
  "function": "function",
  "line": 0
}

All other errors are marshaled in to a generic JSON object:

// The "generic" version of an error
{
  "error": "the output of Error() string",
  "wraps": { /* another error or null */ }
}

๐Ÿ—’ Formatting Errors

Errors have a Format method that returns a string with a custom format. It takes an error format string, ef, that is built using error format tokens.

For example, you can achieve the same output as the caller's description by using the following format,

ef := fmt.Sprintf(
  "%s (%s:%s)",
  ErrorFormatTokenFunction,
  ErrorFormatTokenFile,
  ErrorFormatTokenLine,
)

// The following statments have the same output
fmt.Println(e.Format(ef))
fmt.Println(e.Caller)

or you can create more complex/custom error formats.

ef := fmt.Sprintf(
  "Error #%s at %s (%s:%s): %s",
  ErrorFormatTokenIndex,
  ErrorFormatTokenTime,
  ErrorFormatTokenFile,
  ErrorFormatTokenLine,
  ErrorFormatTokenChain,
)

fmt.Println(e.Format(ef))
Error #2 at 2021-03-07 16:39:56.393366 -0600 CST m=+0.001129674 (formatter_test.go:10): error 2: error 1

The available tokens are as follows.

Token Description
ErrorFormatTokenContext The error's context.
ErrorFormatTokenInner The output of the inner error's Error method.
ErrorFormatTokenChain The error chain as returned by the error's Error method.
ErrorFormatTokenFile The file name from the error's caller.
ErrorFormatTokenFunction The function from the error's caller.
ErrorFormatTokenLine The line number from the error's caller.
ErrorFormatTokenStack The stack trace from the error's caller.
ErrorFormatTokenSource The source fragment from the error's caller.
ErrorFormatTokenTime The time from the error's metadata.
ErrorFormatTokenDuration The duration (in seconds) from the error's metadata.
ErrorFormatTokenIndex The error's index.
ErrorFormatTokenSimilar The number of similar errors.
ErrorFormatTokenRoutines The number of goroutines when the error was created.
ErrorFormatTokenCPUs The number of available CPUs when the error was created.
ErrorFormatTokenCGO The number of cgo calls when the error was created.
ErrorFormatTokenMemory The process memory statistics when the error was created.
ErrorFormatTokenSeverityTitle The detected error severity title.
ErrorFormatTokenSeverityLevel The detected error severity level.

๐ŸŽ› Configuring Errors

The package's configuration is accessible through the global Config function.

Use the Set method to configure everything at once, or any of the corresponding setters to the getters listed in the table below.

// Configure the package to
// - Capture call information
// - Ignore process information
// - Collect source fragments
// - Get 9 lines of source
// - Ignore breakpoints
// - Start indexing errors at 1
// - Track similar errors
// - Marshal full errors in to JSON
we.Config().Set(true, false, true, 4, true, 1, true, false)

To return to the initial state upon launch, use the ResetState function. Resetting state resets all configuration variables, the process launch time, and the hash map for keeping track for similar wrapped errors.

// Reset the package's state and configuration.
we.ResetState()
Function Initial Value Description
CaptureCaller() bool true Determines whether or not new errors will capture their call information. If you don't need to capture call information, you can set this to false. Be advised, future calls to Caller on new errors will return nil.
CaptureProcess() bool true Determines whether or not new errors will capture process information. If you don't need to capture process information, you can set this to false. Same as CaptureCaller, future calls to Process on new errors will return nil.
CaptureSourceFragments true Determines whether or not new errors will capture source code around the line that the error was created on.
SourceFragmentRadius() int 2 The line radius of source fragments collected during debugging. For example, if the error is created on line 15 in a file, then (using the default radius of 2) source would be collected from lines 13 through 17.
IgnoreBreakpoints() bool true Determines whether or not breakpoints should be ignored when calling Process.Break.
NextErrorIndex() int 1 The next index that will be used when creating an error in the error's metadata.
TrackSimilarErrors() bool true Whether or not errors that are wrapped should be tracked for similarity.
MarshalMinimalJSON() bool true Determines how errors are marshaled in to JSON. When this value is true, a smaller JSON object is created without size-inflating data like stack traces and source fragments.

๐Ÿงต Thread Safety

The package was built with thread-safety in mind. You can modify configuration settings and create errors from any goroutine without worrying about locks.

๐Ÿ‘ฅ Contributing

Feel free to contribute either through reporting issues or submitting pull requests.

Thank you to @GregWWalters for ideas, tips and advice.

Documentation ยถ

Index ยถ

Constants ยถ

This section is empty.

Variables ยถ

View Source
var ErrRegexRequired = errors.New("regex required")

ErrRegexRequired indicates that a regular expression is required.

View Source
var ErrSeverityAlreadyRegistered = errors.New("severity already registered")

ErrSeverityAlreadyRegistered indicates that the error severity has already been registered.

Functions ยถ

func RegisterErrorSeverity ยถ

func RegisterErrorSeverity(severity ErrorSeverity) error

RegisterErrorSeverity registers the error severity with the package. If the severity has already been registered, then a ErrSeverityAlreadyRegistered error is returned.

func ResetState ยถ

func ResetState()

ResetState resets the package's state to that at process launch.

func UnregisterErrorSeverity ยถ

func UnregisterErrorSeverity(severity ErrorSeverity)

UnregisterErrorSeverity unregisters the error severity from the package. If the severity wasn't already registered, then this function does nothing.

Types ยถ

type Caller ยถ

type Caller struct {

	// The caller's file.
	File string `json:"file"`

	// The caller's function name.
	Function string `json:"function"`

	// The caller's line number.
	Line int `json:"line"`

	// A stack trace of the goroutine that created the caller.
	StackTrace string `json:"stackTrace"`

	// Source returns raw source code around the line that the caller was created
	// on. This function will return an empty string if the process is not
	// currently being debugged.
	SourceFragment string `json:"sourceFragment"`
}

Caller types contain call information.

func (Caller) String ยถ

func (c Caller) String() string

type Configuration ยถ

type Configuration struct {
	// contains filtered or unexported fields
}

Configuration types keep track of the package's configuration.

func Config ยถ

func Config() *Configuration

Config returns the package's configuration.

func (*Configuration) CaptureCaller ยถ

func (c *Configuration) CaptureCaller() bool

CaptureCaller gets a boolean that indicates whether or not new errors capture their caller information.

func (*Configuration) CaptureProcess ยถ

func (c *Configuration) CaptureProcess() bool

CaptureProcess gets a boolean that indicates whether or not new errors capture their process information.

func (*Configuration) CaptureSourceFragments ยถ

func (c *Configuration) CaptureSourceFragments() bool

CaptureSourceFragments gets a boolean that indicates whether or not new errors capture source fragments.

func (*Configuration) IgnoreBreakpoints ยถ

func (c *Configuration) IgnoreBreakpoints() bool

IgnoreBreakpoints returns whether or not calls to `Break` on `Process` types will be ignored. This value defaults to true.

func (*Configuration) MarshalMinimalJSON ยถ

func (c *Configuration) MarshalMinimalJSON() bool

MarshalMinimalJSON gets a boolean that indicates whether or not errors will be marshaled in to a minimal version of JSON.

func (*Configuration) NextErrorIndex ยถ

func (c *Configuration) NextErrorIndex() int

NextErrorIndex gets the next error index that will be used when creating an error.

func (*Configuration) Set ยถ

func (c *Configuration) Set(
	captureCaller bool,
	captureProcess bool,
	captureSourceFragments bool,
	sourceFragmentRadius int,
	ignoreBreakpoints bool,
	nextErrorIndex int,
	trackSimilarErrors bool,
	marshalMinimalJSON bool,
)

Set configures the behavior of various aspects of the wrappederror package at once.

Configure individual properties using the Set(Property) methods.

func (*Configuration) SetCaptureCaller ยถ

func (c *Configuration) SetCaptureCaller(capture bool)

SetCaptureCaller sets a flag to determine if new errors capture their caller information.

func (*Configuration) SetCaptureProcess ยถ

func (c *Configuration) SetCaptureProcess(capture bool)

SetCaptureProcess sets a flag to determine if new errors capture their process information.

func (*Configuration) SetCaptureSourceFragments ยถ

func (c *Configuration) SetCaptureSourceFragments(capture bool)

SetCaptureSourceFragments sets a flag to determine whether or not new errors capture source fragments.

func (*Configuration) SetIgnoreBreakpoints ยถ

func (c *Configuration) SetIgnoreBreakpoints(ignore bool)

SetIgnoreBreakpoints tells all calls to `Break` on `Process` types to either handle or ignore invocations.

func (*Configuration) SetMarshalMinimalJSON ยถ

func (c *Configuration) SetMarshalMinimalJSON(minimal bool)

SetMarshalMinimalJSON determines how errors are marshaled in to JSON. When this value is true, a smaller JSON object is created without size-inflating data like stack traces and source fragments.

func (*Configuration) SetNextErrorIndex ยถ

func (c *Configuration) SetNextErrorIndex(index int)

SetNextErrorIndex sets the next error index that will be used when creating an error.

func (*Configuration) SetSourceFragmentRadius ยถ

func (c *Configuration) SetSourceFragmentRadius(radius int)

SetSourceFragmentRadius sets the radius of the source fragment obtained from source files at the line that the caller was created on.

func (*Configuration) SetTrackSimilarErrors ยถ

func (c *Configuration) SetTrackSimilarErrors(track bool)

SetTrackSimilarErrors enables or prohibits similar error tracking.

func (*Configuration) SourceFragmentRadius ยถ

func (c *Configuration) SourceFragmentRadius() int

SourceFragmentRadius gets the radius of source fragments obtained from source files.

func (*Configuration) TrackSimilarErrors ยถ

func (c *Configuration) TrackSimilarErrors() bool

TrackSimilarErrors returns whether or not similar errors are being tracked.

type Error ยถ

type Error struct {

	// The error's caller.
	//
	// Use this value to examine the error's call information such as file name,
	// function name, line number, stack trace and source fragment.
	//
	// Call information is captured by default. To not capture this information,
	// use the SetCaptureCaller configuration method.
	//
	// If call information is not captured, then this property is nil.
	Caller *Caller

	// Process information at the time the error was created.
	//
	// Use this value to examine the current process's information such as number
	// of goroutines, available logical CPUs, memory statistics, and so forth.
	//
	// Process information is captured by default. To not capture this
	// information, use the SetCaptureProcess configuration method.
	//
	// If process information is not captured, then this property is nil.
	Process *Process

	// Metadata pertaining to the error.
	//
	// Use this value to examine general properties about the error such as its
	// index, timestamp, and how many other similar errors have been created.
	//
	// Metadata is always captured, but some of its properties are configurable.
	Metadata *Metadata
	// contains filtered or unexported fields
}

Error types wrap an error and provide context, caller and process information.

func New ยถ

func New(err error, ctx interface{}) *Error

New creates and returns a new error with an inner error and context.

func (Error) As ยถ

func (e Error) As(target interface{}) bool

As finds the first error in the error chain that matches target, and if so, sets target to that error value and returns true. Otherwise, it returns false.

func (Error) Chain ยถ

func (e Error) Chain() []error

Chain returns the error chain as a slice with the receiver at index 0.

func (Error) Context ยถ

func (e Error) Context() interface{}

Context returns the error's context.

func (Error) Depth ยถ

func (e Error) Depth() uint

Depth returns the number of nested errors in the receiver. That is, the number of errors after, but not including, this error in the error chain.

For example, if an error has no nested errors, then its depth is 0.

func (Error) Error ยถ

func (e Error) Error() string

func (Error) ErrorWithDepth ยถ

func (e Error) ErrorWithDepth(depth int) error

ErrorWithDepth returns the error in the chain with the given depth.

func (Error) ErrorWithIndex ยถ

func (e Error) ErrorWithIndex(index int) error

ErrorWithIndex returns the error in the chain with the given index. This is the inverse index of depth.

For example, if the error chain is [e0, e1, e2] with depths [2, 1, 0], then the error at index 0 is e0, the error at index 1 is e1, and so forth.

func (Error) Format ยถ

func (e Error) Format(ef string) string

Format returns a formatted string representation of the error using the error format string, ef.

You create an error format string by building a string with ErrorFormatToken types.

Do not use formatting verbs supported by the fmt package in the error format string.

func (Error) Is ยถ

func (e Error) Is(target error) bool

Is reports whether any error in the error chain matches target.

The chain consists of the receiver followed by the sequence of errors obtained by repeatedly calling Unwrap.

The receiver 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 (Error) MarshalJSON ยถ

func (e Error) MarshalJSON() ([]byte, error)

MarshalJSON marshals the error in to JSON data.

func (Error) Trace ยถ

func (e Error) Trace() string

Trace returns a prettified string representation of the error chain.

func (Error) Unwrap ยถ

func (e Error) Unwrap() error

Unwrap returns the wrapped error or nil if one doesn't exist.

func (Error) Walk ยถ

func (e Error) Walk(step func(err error) bool)

Walk calls the step function for each error in the error chain, including the receiver, and continues until either the last error is reached, or the step function returns false.

type ErrorFormatToken ยถ

type ErrorFormatToken string

ErrorFormatToken types specify a token that can be used to format an error string.

const (

	// ErrorFormatTokenContext prints the error's context.
	ErrorFormatTokenContext ErrorFormatToken = "${{CTX}}"

	// ErrorFormatTokenInner prints the error's context.
	ErrorFormatTokenInner ErrorFormatToken = "${{INN}}"

	// ErrorFormatTokenChain prints the error's context.
	ErrorFormatTokenChain ErrorFormatToken = "${{CHN}}"

	// ErrorFormatTokenFile prints the error's context.
	ErrorFormatTokenFile ErrorFormatToken = "${{FIL}}"

	// ErrorFormatTokenFunction prints the error's context.
	ErrorFormatTokenFunction ErrorFormatToken = "${{FUN}}"

	// ErrorFormatTokenLine prints the error's context.
	ErrorFormatTokenLine ErrorFormatToken = "${{LIN}}"

	// ErrorFormatTokenStack prints the error's context.
	ErrorFormatTokenStack ErrorFormatToken = "${{STK}}"

	// ErrorFormatTokenSource prints the error's context.
	ErrorFormatTokenSource ErrorFormatToken = "${{SRC}}"

	// ErrorFormatTokenTime prints the error's context.
	ErrorFormatTokenTime ErrorFormatToken = "${{TIM}}"

	// ErrorFormatTokenDuration prints the error's context.
	ErrorFormatTokenDuration ErrorFormatToken = "${{DUR}}"

	// ErrorFormatTokenIndex prints the error's context.
	ErrorFormatTokenIndex ErrorFormatToken = "${{IDX}}"

	// ErrorFormatTokenSimilar prints the error's context.
	ErrorFormatTokenSimilar ErrorFormatToken = "${{SIM}}"

	// ErrorFormatTokenRoutines prints the error's context.
	ErrorFormatTokenRoutines ErrorFormatToken = "${{RTS}}"

	// ErrorFormatTokenCPUs prints the error's context.
	ErrorFormatTokenCPUs ErrorFormatToken = "${{CPU}}"

	// ErrorFormatTokenCGO prints the error's context.
	ErrorFormatTokenCGO ErrorFormatToken = "${{CGO}}"

	// ErrorFormatTokenMemory prints the error's context.
	ErrorFormatTokenMemory ErrorFormatToken = "${{MEM}}"

	// ErrorFormatTokenSeverityTitle prints the error's severity title.
	ErrorFormatTokenSeverityTitle ErrorFormatToken = "${{SET}}"

	// ErrorFormatTokenSeverityLevel prints the error's severity level.
	ErrorFormatTokenSeverityLevel ErrorFormatToken = "${{SEL}}"
)

A group of error format tokens.

type ErrorSeverity ยถ

type ErrorSeverity struct {

	// The severity's title.
	Title string `json:"title"`

	// The regular expression used to match against `Error` method strings.
	Regex *regexp.Regexp `json:"regex"`

	// The severity level.
	Level ErrorSeverityLevel `json:"level"`
}

ErrorSeverity types define an error severity with a title, level, and a regular expression that is used to find matches in an error's `Error` method output.

func NewErrorSeverity ยถ

func NewErrorSeverity(
	title string,
	regex string,
	level ErrorSeverityLevel,
) (ErrorSeverity, error)

NewErrorSeverity creates and returns a new error severity with the given title, level and regular expression. If the regular expression is invalid, this function will return an error and an unknown error severity.

func (ErrorSeverity) String ยถ

func (s ErrorSeverity) String() string

type ErrorSeverityLevel ยถ

type ErrorSeverityLevel string

ErrorSeverityLevel types define an error severity level.

const (
	ErrorSeverityLevelNone     ErrorSeverityLevel = "none"
	ErrorSeverityLevelLow      ErrorSeverityLevel = "low"
	ErrorSeverityLevelModerate ErrorSeverityLevel = "moderate"
	ErrorSeverityLevelHigh     ErrorSeverityLevel = "high"
	ErrorSeverityLevelSevere   ErrorSeverityLevel = "severe"
)

A group of error severity levels.

type Metadata ยถ

type Metadata struct {

	// The time that the error was created.
	Time time.Time `json:"time"`

	// The duration since the process was launched and when the error was created.
	//
	// This value mimics the monotonic clock reading appended to the end of
	// strings returned by the `time.String() string` method. There will be a
	// slight difference in duration depending on the executable's package loading
	// order.
	Duration time.Duration `json:"duration"`

	// The index of the error.
	//
	// Error indexes begin at 1 and incriment for each error created during the
	// process's execution.
	//
	// To start at a different index, use the `SetNextErrorIndex` function.
	Index int `json:"index"`

	// The number of similar errors when this error was created.
	//
	// A similar error is an error that has the same inner error. A hashmap is
	// maintained of inner error `Error() string` value hashes.
	//
	// To turn this off, use the `SetTrackSimilarErrors` function. When tracking
	// is off, this method always returns 0.
	Similar int `json:"similar"`

	// The package automatically detects the severity of errors based on
	// ErrorSeverity instances registered through the package's configuration.
	Severity *ErrorSeverity `json:"severity,omitempty"`
}

Metadata types contain metadata about an error.

func (Metadata) String ยถ

func (m Metadata) String() string

type Process ยถ

type Process struct {

	// The number of go routines.
	Routines int `json:"goroutines"`

	// The number of available logical CPUs.
	CPUs int `json:"cpus"`

	// The number of cgo calls made by the process.
	CGO int `json:"cgos"`

	// Memory statistics about the process.
	Memory *runtime.MemStats `json:"memory,omitempty"`
}

Process types contain process information at their time of creation.

func (Process) Break ยถ

func (p Process) Break()

Break executes a breakpoint trap if the configuration's ignore breakpoints value is false.

func (Process) String ยถ

func (p Process) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL