errors

package
v0.0.0-...-0db00f2 Latest Latest
Warning

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

Go to latest
Published: Dec 20, 2024 License: AGPL-3.0 Imports: 5 Imported by: 0

Documentation

Overview

Package errors implements a set of error helpers and proxies on to standard go errors for use within Juju.

Package level errors through out Juju can be made by using ConstError

package MyPackage

const (
	MyFabulousError = ConstError("sparkling")
)

return Errorf("this error %w happened", MyFabulousError)

Errors can be extended further by turning a given error into a Error type. Error types are obtained by first annotating an already existing error with more context with Errorf, creating a new error with New or combining a set of errors with Join.

In this package there exists several helper types for checking an error chain. AsType allows the caller to check if there is an error of a given type T in the chain and returns back a copy of T if the type was found. HasType is the same as AsType but instead of returning T only a bool indicating if T was found is returned.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func As

func As(err error, target any) bool

As finds the first error in err's tree that matches target, and if one is found, sets target to that error value and returns true. Otherwise, it returns false.

The tree consists of err itself, followed by the errors obtained by repeatedly calling its Unwrap() error or Unwrap() []error method. When err wraps multiple errors, As examines err followed by a depth-first traversal of its children.

An error matches target if the error's concrete value is assignable to the value pointed to by target, or if the error has a method As(interface{}) bool such that As(target) returns true. In the latter case, the As method is responsible for setting target.

An error type might provide an As method so it can be treated as if it were a different error type.

As panics if target is not a non-nil pointer to either a type that implements error, or to any interface type.

As is a proxy for pkg/errors.As and does not alter the semantics offered by this function.

func AsType

func AsType[T error](err error) (T, bool)

AsType finds the first error in err's chain that is assignable to type T, and if a match is found, returns that error value and true. Otherwise, it returns T's zero value and false.

AsType is equivalent to errors.As, but uses a type parameter and returns the target, to avoid having to define a variable before the call. For example, callers can replace this:

var pathError *fs.PathError
if errors.As(err, &pathError) {
    fmt.Println("Failed at path:", pathError.Path)
}

With:

if pathError, ok := errors.AsType[*fs.PathError](err); ok {
    fmt.Println("Failed at path:", pathError.Path)
}
Example
pErr := fs.PathError{
	Path: "/dev/null",
}

err := Errorf("wrapped path error: %w", &pErr)
if pathErr, ok := AsType[*fs.PathError](err); ok {
	fmt.Printf("path error with path %s", pathErr.Path)
}
Output:

path error with path /dev/null

func ErrorStack

func ErrorStack(err error) string

ErrorStack recursively unwinds an error chain by repeatedly calling stderrors.Unwrap until no new errors are returned. A new line is outputted to the resultant string for each error in the chain. If an error in the chain has been traced the errors location information will also be outputted with the error message.

func HasType

func HasType[T error](err error) bool

HasType is a function wrapper around AsType dropping the return value T from AsType() making a function that can be used like:

return HasType[*MyError](err)

Or

if HasType[*MyError](err) {}
Example
pErr := fs.PathError{
	Path: "/dev/null",
}

err := Errorf("wrapped path error: %w", &pErr)
fmt.Println(HasType[*fs.PathError](err))
Output:

true

func Is

func Is(err, target error) bool

Is reports whether any error in err's tree matches target.

The tree consists of err itself, followed by the errors obtained by repeatedly calling its Unwrap() error or Unwrap() []error method. When err wraps multiple errors, Is examines err followed by a depth-first traversal of its children.

An error is 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.

An error type might provide an Is method so it can be treated as equivalent to an existing error. For example, if MyError defines

func (m MyError) Is(target error) bool { return target == fs.ErrExist }

then Is(MyError{}, fs.ErrExist) returns true. See syscall.Errno.Is for an example in the standard library. An Is method should only shallowly compare err and the target and not call Unwrap on either.

Is is a proxy for pkg/errors.Is and does not alter the semantics offered by this function.

func IsOneOf

func IsOneOf(err error, targets ...error) bool

IsOneOf reports whether any error in err's tree matches one of the target errors. This check works on a first match effort in that the first target error discovered reports back true with no further errors.

If targets is empty then this func will always return false.

IsOneOf is the same as writing Is(err, type1) || Is(err, type2) || Is(err, type3)

func Unwrap

func Unwrap(err error) error

Unwrap returns the result of calling the Unwrap method on err, if err's type contains an Unwrap method returning error. Otherwise, Unwrap returns nil.

Unwrap only calls a method of the form "Unwrap() error". In particular Unwrap does not unwrap errors returned by Join

Types

type ConstError

type ConstError string

ConstError is a type for representing static const errors that are best composed as strings.

They're great for package level errors where a package needs to indicate that a certain type of problem to the caller. Const errors are immutable and always comparable.

Example
notFound := ConstError("not found")

err := fmt.Errorf("flux capacitor %w", notFound)
fmt.Println(errors.Is(err, notFound))
fmt.Println(notFound == ConstError("not found"))
Output:

true
true

func (ConstError) Error

func (e ConstError) Error() string

Error returns the constant error string encapsulated by ConstError.

Error also implements the [error] interface.

type Error

type Error interface {
	// error is the error being wrapped.
	error

	// Add will introduce a new error into the error chain so that subsequent
	// calls to As() and Is() will be satisfied for this additional error. The
	// error being added here will not appear in the error output from Error().
	// Unwrap() does not unwrap errors that have been added.
	Add(err error) Error

	// Unwrap returns the underlying error being enriched by this interface.
	Unwrap() error
}

Error provides a way to enrich an already existing Go error and inject new information into the errors chain. Error and its operations are all immutable to the encapsulated error value.

func Errorf

func Errorf(format string, a ...any) Error

Errorf implements a straight through proxy for pkg/fmt.Errorf. The one change this function signature makes is that a type of Error is returned so that the resultant error can be further annotated.

func Join

func Join(errs ...error) Error

Join returns an error that wraps the given errors. Any nil error values are discarded. Join returns nil if every value in errs is nil. The error formats as the concatenation of the strings obtained by calling the Error method of each element of errs, with a newline between each string.

A non-nil error returned by Join implements the Unwrap() []error method.

Join is a proxy for pkg/errors.Join with the difference being that the resultant error is of type Error

func New

func New(text string) Error

New returns an error that formats as the given text. Each call to New returns a distinct error value even if the text is identical.

New is a proxy for pkg/errors.New. All errors returned from New are traced.

type Traced

type Traced interface {
	error

	// Location returns the path-qualified function name where the error was
	// created and the line number
	Location() (function string, line int)
}

Traced represents an error that has had its location recorded for where the error was raised. This is useful for recording error stacks for errors that have not been annotated with contextual information as they flow through a programs stack.

func Capture

func Capture(err error) Traced

Capture is responsible for recording the location where this function was called from in the error supplied. This allows errors that are being passed up through a stack to have extra information attached to them at call sites.

Captured errors should only be used in scenario's where adding extra context to an error is not necessary or can't be done.

ErrorStack can be used to gather all of the capture sites about an error.

Jump to

Keyboard shortcuts

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