errors

package module
v1.5.1 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2023 License: MIT Imports: 9 Imported by: 2,394

README

go-errors/errors

Build Status

Package errors adds stacktrace support to errors in go.

This is particularly useful when you want to understand the state of execution when an error was returned unexpectedly.

It provides the type *Error which implements the standard golang error interface, so you can use this library interchangeably with code that is expecting a normal error return.

Usage

Full documentation is available on godoc, but here's a simple example:

package crashy

import "github.com/go-errors/errors"

var Crashed = errors.Errorf("oh dear")

func Crash() error {
    return errors.New(Crashed)
}

This can be called as follows:

package main

import (
    "crashy"
    "fmt"
    "github.com/go-errors/errors"
)

func main() {
    err := crashy.Crash()
    if err != nil {
        if errors.Is(err, crashy.Crashed) {
            fmt.Println(err.(*errors.Error).ErrorStack())
        } else {
            panic(err)
        }
    }
}

Meta-fu

This package was original written to allow reporting to Bugsnag from bugsnag-go, but after I found similar packages by Facebook and Dropbox, it was moved to one canonical location so everyone can benefit.

This package is licensed under the MIT license, see LICENSE.MIT for details.

Changelog

  • v1.1.0 updated to use go1.13's standard-library errors.Is method instead of == in errors.Is
  • v1.2.0 added errors.As from the standard library.
  • v1.3.0 BREAKING updated error methods to return error instead of *Error.

Code that needs access to the underlying *Error can use the new errors.AsError(e)

  // before
  errors.New(err).ErrorStack()
  // after
.  errors.AsError(errors.Wrap(err)).ErrorStack()
  • v1.4.0 BREAKING v1.4.0 reverted all changes from v1.3.0 and is identical to v1.2.0
  • v1.4.1 no code change, but now without an unnecessary cover.out file.
  • v1.4.2 performance improvement to ErrorStack() to avoid unnecessary work https://github.com/go-errors/errors/pull/40
  • v1.5.0 add errors.Join() and errors.Unwrap() copying the stdlib https://github.com/go-errors/errors/pull/40
  • v1.5.1 fix build on go1.13..go1.19 (broken by adding Join and Unwrap with wrong build constraints)

Documentation

Overview

Package errors provides errors that have stack-traces.

This is particularly useful when you want to understand the state of execution when an error was returned unexpectedly.

It provides the type *Error which implements the standard golang error interface, so you can use this library interchangably with code that is expecting a normal error return.

For example:

package crashy

import "github.com/go-errors/errors"

var Crashed = errors.Errorf("oh dear")

func Crash() error {
    return errors.New(Crashed)
}

This can be called as follows:

package main

import (
    "crashy"
    "fmt"
    "github.com/go-errors/errors"
)

func main() {
    err := crashy.Crash()
    if err != nil {
        if errors.Is(err, crashy.Crashed) {
            fmt.Println(err.(*errors.Error).ErrorStack())
        } else {
            panic(err)
        }
    }
}

This package was original written to allow reporting to Bugsnag, but after I found similar packages by Facebook and Dropbox, it was moved to one canonical location so everyone can benefit.

Index

Examples

Constants

This section is empty.

Variables

View Source
var MaxStackDepth = 50

The maximum number of stackframes on any error.

Functions

func As added in v1.2.0

func As(err error, target interface{}) 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.

For more information see stdlib errors.As.

func Is

func Is(e error, original error) bool

Is detects whether the error is equal to a given error. Errors are considered equal by this function if they are matched by errors.Is or if their contained errors are matched through errors.Is.

func Join added in v1.5.0

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.

For more information see stdlib errors.Join.

func Unwrap added in v1.5.0

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.

For more information see stdlib errors.Unwrap.

Types

type Error

type Error struct {
	Err error
	// 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 Errorf

func Errorf(format string, a ...interface{}) *Error

Errorf creates a new error with the given message. You can use it as a drop-in replacement for fmt.Errorf() to provide descriptive errors in return values.

func New

func New(e interface{}) *Error

New makes an Error from the given value. If that value is already an error then it will be used directly, if not, it will be passed to fmt.Errorf("%v"). The stacktrace will point to the line of code that called New.

func ParsePanic

func ParsePanic(text string) (*Error, error)

ParsePanic allows you to get an error object from the output of a go program that panicked. This is particularly useful with https://github.com/mitchellh/panicwrap.

func Wrap

func Wrap(e interface{}, skip int) *Error

Wrap makes an Error from the given value. If that value is already an error then it will be used directly, if not, it will be passed to fmt.Errorf("%v"). The skip parameter indicates how far up the stack to start the stacktrace. 0 is from the current call, 1 from its caller, etc.

Example
if err := recover(); err != nil {
	return Wrap(err, 1)
}

return a()
Output:

func WrapPrefix

func WrapPrefix(e interface{}, prefix string, skip int) *Error

WrapPrefix makes an Error from the given value. If that value is already an error then it will be used directly, if not, it will be passed to fmt.Errorf("%v"). The prefix parameter is used to add a prefix to the error message when calling Error(). The skip parameter indicates how far up the stack to start the stacktrace. 0 is from the current call, 1 from its caller, etc.

func (*Error) Callers

func (err *Error) Callers() []uintptr

Callers satisfies the bugsnag ErrorWithCallerS() interface so that the stack can be read out.

func (*Error) Error

func (err *Error) Error() string

Error returns the underlying error's message.

func (*Error) ErrorStack

func (err *Error) ErrorStack() string

ErrorStack returns a string that contains both the error message and the callstack.

func (*Error) Stack

func (err *Error) Stack() []byte

Stack returns the callstack formatted the same way that go does in runtime/debug.Stack()

func (*Error) StackFrames

func (err *Error) StackFrames() []StackFrame

StackFrames returns an array of frames containing information about the stack.

func (*Error) TypeName

func (err *Error) TypeName() string

TypeName returns the type this error. e.g. *errors.stringError.

func (*Error) Unwrap added in v1.2.0

func (err *Error) Unwrap() error

Return the wrapped error (implements api for As function).

type StackFrame

type StackFrame struct {
	// The path to the file containing this ProgramCounter
	File string
	// The LineNumber in that file
	LineNumber int
	// The Name of the function that contains this ProgramCounter
	Name string
	// The Package that contains this function
	Package string
	// The underlying ProgramCounter
	ProgramCounter uintptr
}

A StackFrame contains all necessary information about to generate a line in a callstack.

func NewStackFrame

func NewStackFrame(pc uintptr) (frame StackFrame)

NewStackFrame popoulates a stack frame object from the program counter.

func (*StackFrame) Func

func (frame *StackFrame) Func() *runtime.Func

Func returns the function that contained this frame.

func (*StackFrame) SourceLine

func (frame *StackFrame) SourceLine() (string, error)

SourceLine gets the line of code (from File and Line) of the original source if possible.

func (*StackFrame) String

func (frame *StackFrame) String() string

String returns the stackframe formatted in the same way as go does in runtime/debug.Stack()

Jump to

Keyboard shortcuts

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