errors

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 7, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

README

errors

The errors module augments Go's standard errors package to capture stack traces and associate HTTP status codes and arbitrary properties with errors. For this purpose, it overrides and extends the standard errors.New constructor.

import "github.com/microbus-io/errors" // instead of "errors"

err := errors.New("my error") // err is augmented with the stack trace of this line

err = errors.New("error in process '%s'", processName) // err is augmented with the stack trace of this line

The errors module redefines all the methods in Go's standard errors package which allow seamlessly replacing import "errors" with import "github.com/microbus-io/errors".

errors.Trace augments standard Go errors with the stack trace.

import "github.com/microbus-io/errors"

fileName := "non/existent.file"
body, err := io.ReadAll(fileName) // err is a standard Go error
err = errors.Trace(err) // err is now augmented with the stack trace of this line

Alternatively, errors.New can be used to wrap the error as if with fmt.Errof("message: %w", err) before augmenting it with the stack trace.

import "github.com/microbus-io/errors"

fileName := "non/existent.file"
body, err := io.ReadAll(fileName) // err is a standard Go error
err = errors.New("failed to read %s", fileName, err) // err now wraps the original err and captures the stack trace

An HTTP status code can be attached to an error with either errors.New or errors.Trace. It can then be retrieved up the stack to respond to HTTP requests.

notFound := errors.New("nothing to see here", http.StatusNotFound)

body, err := io.ReadAll("non/existent.file") // err is a standard Go error
err = errors.Trace(err, http.StatusNotFound) // err is now augmented with the stack trace of this line and the status code

statusCode := errors.StatusCode(err) // Retrieve the status code

Both errors.New and errors.Trace allow associating arbitrary properties with errors. Properties are not part of the error's Error() message. Rather, they can be retrieved up the call stack in a structured way. A common use case is associating an error code or a human-friendly message, and using a middleware to render custom error responses.

fileName := "non/existent.file"
body, err := io.ReadAll(fileName) // err is a standard Go error
err = errors.Trace(err
	"name", fileName, // err is now augmented with a property
)

fileName := errors.Convert(err).Properties["name"] // Retrieve the property

The fmt verb %v is equivalent to the err.Error() message and prints the error message. The extended verb %+v is equivalent to errors.Convert(err).String() and print the stack trace, status code and associated properties.

strconv.ParseInt: parsing "nan": invalid syntax
statusCode=400

- calculator.(*Service).Square
  /src/github.com/microbus-io/fabric/examples/calculator/service.go:75
- connector.(*Connector).onRequest
  /src/github.com/microbus-io/fabric/connector/messaging.go:225
- connector.(*Connector).Publish
  /src/github.com/microbus-io/fabric/connector/messaging.go:94
- httpingress.(*Service).ServeHTTP
  /src/github.com/microbus-io/fabric/coreservices/httpingress/service.go:124

CatchPanic is a utility function that converts panics into standard errors.

err = errors.CatchPanic(func() error {
    panic("oops!")
    return nil
})

Documentation

Overview

Package errors replaces the standard Go package, adding the ability to attach a stack trace, status code, and arbitrary properties to an error.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func As

func As(err error, target any) bool

As delegates to the standard Go's errors.As function.

func CatchPanic

func CatchPanic(f func() error) (err error)

CatchPanic calls the given function and returns any panic as a standard error.

err = errors.CatchPanic(func() error {
	panic("oops!")
	return nil
})

func Is

func Is(err, target error) bool

Is delegates to the standard Go's errors.Is function.

func Join

func Join(errs ...error) error

Join aggregates multiple errors into one. The stack traces of the original errors are discarded and a new stack trace is captured.

func New

func New(pattern string, args ...any) error

New creates a new error, with a static or formatted message, optionally wrapping another error, attaching a status code or attaching properties.

In the simplest case, the pattern is a static string.

New("network timeout")

If the pattern contains % signs, the next appropriate number of arguments are used to format the message of the new error as if with fmt.Errorf.

New("failed to parse '%s' for user %d", dateStr, userID)

Any additional arguments are treated like slog name=value pairs and added to the error's property bag. Properties are not part of the error's message and can be retrieved up the call stack in a structured way.

New("failed to execute '%s'", cmd,
	"exitCode", exitCode,
	"os", os,
)

Three notable properties do not require a name: errors, integers and 32-character long hex string.

New("failed to parse form",
	err,
	http.StatusBadRequest,
	"ba0da7b3d3150f20702229c4521b58e9",
	"path", r.URL.Path,
)

An unnamed error is interpreted to be the original source of the error. The new error is created to wrap the original error as if with

fmt.Errorf(errorMessage+": %w", originalError)

An unnamed integer is interpreted to be an HTTP status code to associate with the error. If the pattern is empty, the status text is set by default.

An unnamed 32-character long hex string is interpreted to be a trace ID.

func StatusCode

func StatusCode(err error) int

StatusCode returns the HTTP status code associated with an error. It is the equivalent of Convert(err).StatusCode. The default status code is 500.

func Trace

func Trace(err error, a ...any) error

Trace appends the current stack location to the error's stack trace. The variadic arguments behave like those of New.

func Unwrap

func Unwrap(err error) error

Unwrap delegates to the standard Go's errors.Wrap function.

Types

type StackFrame

type StackFrame struct {
	Function string `json:"func"`
	File     string `json:"file"`
	Line     int    `json:"line"`
}

StackFrame is a single stack location.

func (*StackFrame) String

func (t *StackFrame) String() string

String returns a string representation of the stack frame.

type StreamedError

type StreamedError struct {
	Error      string        `json:"error" jsonschema:"example=message"`
	StatusCode int           `json:"statusCode,omitzero"`
	Trace      string        `json:"trace,omitzero"`
	Stack      []*StackFrame `json:"stack,omitzero"`
}

StreamedError is the schema used to marshal and unmarshal the traced error.

type TracedError

type TracedError struct {
	Err        error
	Stack      []*StackFrame
	StatusCode int
	Trace      string
	Properties map[string]any
}

TracedError is a standard Go error augmented with a stack trace, status code and property bag.

func Convert

func Convert(err error) *TracedError

Convert converts an error to one that supports stack tracing. If the error already supports this, it is returned as it is. Note: Trace should be called to include the error's trace in the stack.

func (*TracedError) Error

func (e *TracedError) Error() string

Error returns the error string.

func (*TracedError) Format

func (e *TracedError) Format(s fmt.State, verb rune)

Format the error based on the verb and flag.

func (*TracedError) MarshalJSON

func (e *TracedError) MarshalJSON() ([]byte, error)

MarshalJSON marshals the error to JSON.

func (*TracedError) String

func (e *TracedError) String() string

String returns a human-friendly representation of the traced error.

func (*TracedError) UnmarshalJSON

func (e *TracedError) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals the error from JSON. Neither the type of the error nor any errors it wraps can be restored.

func (*TracedError) Unwrap

func (e *TracedError) Unwrap() error

Unwrap returns the underlying error.

Jump to

Keyboard shortcuts

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