Documentation
¶
Overview ¶
Package xerrors is a small, idiomatic library that makes error handling in Go easier. It provides utilities for creating errors with stack traces, wrapping existing errors, aggregating multiple errors, and recovering from panics.
Index ¶
- Variables
- func Append(err error, errs ...error) error
- func Fprint(w io.Writer, err error) (int, error)
- func FromRecover(r any) error
- func Join(vals ...any) error
- func Joinf(format string, args ...any) error
- func Message(msg string) error
- func Messagef(format string, args ...any) error
- func New(vals ...any) error
- func Newf(format string, args ...any) error
- func Print(err error)
- func Recover(fn func(err error))
- func Sprint(err error) string
- func WithStackTrace(err error, skip int) error
- type Callers
- type DetailedError
- type Frame
- type PanicError
Constants ¶
This section is empty.
Variables ¶
var DefaultCallersFormatter = func(c Callers, w io.Writer) { for _, frame := range c.Frames() { io.WriteString(w, "at ") frame.writeFrame(w) io.WriteString(w, "\n") } }
DefaultCallersFormatter is the default formatter for Callers.
var DefaultFrameFormatter = func(f Frame, w io.Writer) { io.WriteString(w, shortname(f.Function)) io.WriteString(w, " (") io.WriteString(w, f.File) io.WriteString(w, ":") io.WriteString(w, strconv.Itoa(f.Line)) io.WriteString(w, ")") }
DefaultFrameFormatter is the default formatter for Frame.
Functions ¶
func Append ¶
Append appends the provided errors to an existing error or list of errors. If err is not a multi-error, it is converted into one. Nil errors are ignored. It does not record a stack trace.
The errors passed as arguments are not modified.
If the resulting error list is empty, nil is returned. If the resulting error list contains only one error, that error is returned instead of the list.
The returned error is compatible with Go errors, supporting errors.Is, errors.As, and the Go 1.20 `Unwrap() []error` method.
To create a chained error, use New, Newf, Join, or Joinf instead.
func Fprint ¶
Fprint writes a formatted error to the provided io.Writer. It returns the number of bytes written and any error encountered while writing.
If any error in the chain implements DetailedError and returns a non-empty string, its details are appended to the error message.
If err is nil, nothing is written.
func FromRecover ¶
FromRecover converts the result of the built-in `recover()` into an error with a stack trace. The returned error implements PanicError. It returns nil if `r` is nil.
This function must be called in the same function as `recover()` to ensure that the stack trace is accurate.
func Join ¶ added in v1.0.0
Join joins multiple values into a single error, forming a chain of errors. Each value wraps the one that follows it.
Conversion rules for arguments:
- If the value is an error, it is used as is.
- If the value is a string, a new error with that message is created.
- If the value implements fmt.Stringer, the result of String() is used to create an error.
- If the value is nil, it is ignored.
- Otherwise, the result of fmt.Sprint is used to create an error.
If called with no arguments or only nil values, Join returns nil.
To create a multi-error instead of an error chain, use Append.
func Joinf ¶ added in v1.0.0
Joinf joins multiple values into a single error with a formatted message, forming an error chain. The format string follows the conventions of fmt.Errorf.
Unlike errors created by fmt.Errorf, the Unwrap method on the returned error yields the next wrapped error, not a slice of errors, because this function is intended for creating linear error chains.
To create a multi-error instead of an error chain, use Append.
func Message ¶
Message creates a simple error with the given message, without recording a stack trace. Each call returns a distinct error instance, even if the message is identical.
This function is useful for creating sentinel errors, often referred to as "constant errors."
To create an error with a stack trace, use New or Newf instead.
func Messagef ¶ added in v1.0.0
Messagef creates a simple error with a formatted message, without recording a stack trace. The format string follows the conventions of fmt.Sprintf. Each call returns a distinct error instance, even if the message is identical.
This function is useful for creating sentinel errors, often referred to as "constant errors."
To create an error with a stack trace, use New or Newf instead.
func New ¶
New creates a new error from the provided values and records a stack trace at the point of the call. If multiple values are provided, each value wraps the one that follows it, forming a chain of errors.
Usage examples:
- Add a stack trace to an existing error: New(err)
- Create an error with a message and a stack trace: New("access denied")
- Wrap an error with a message: New("access denied", io.EOF)
- Add context to a sentinel error: New(ErrRead, "access denied")
Conversion rules for arguments:
- If the value is an error, it is used as is.
- If the value is a string, a new error with that message is created.
- If the value implements fmt.Stringer, the result of String() is used to create an error.
- If the value is nil, it is ignored.
- Otherwise, the result of fmt.Sprint is used to create an error.
If called with no arguments or only nil values, New returns nil.
To create a sentinel error, use Message or Messagef instead.
func Newf ¶ added in v1.0.0
Newf creates a new error with a formatted message and records a stack trace at the point of the call. The format string follows the conventions of fmt.Errorf.
Unlike errors created by fmt.Errorf, the Unwrap method on the returned error yields the next wrapped error, not a slice of errors, because this function is intended for creating linear error chains.
To create a sentinel error, use Message or Messagef instead.
func Print ¶
func Print(err error)
Print writes a formatted error to stderr.
If any error in the chain implements DetailedError and returns a non-empty string, its details are appended to the error message.
If err is nil, nothing is written.
func Recover ¶
func Recover(fn func(err error))
Recover wraps the built-in `recover()` function, converting the recovered value into an error with a stack trace. The provided `fn` callback is only invoked when a panic occurs.
This function must always be used directly with the `defer` keyword.
func Sprint ¶
Sprint returns a formatted error as a string.
If any error in the chain implements DetailedError and returns a non-empty string, its details are appended to the error message.
The output may span multiple lines and ends with a newline. If err is nil, an empty string is returned.
func WithStackTrace ¶
WithStackTrace wraps the provided error with a stack trace, capturing the stack at the point of the call. The `skip` argument specifies how many stack frames to skip: 0 starts the stack trace at the caller of WithStackTrace, 1 at its caller, and so on.
If err is nil, WithStackTrace returns nil.
Types ¶
type Callers ¶
type Callers []uintptr
Callers is a stack trace represented as a list of program counters, as returned by runtime.Callers.
func StackTrace ¶
StackTrace extracts the stack trace from the provided error. It traverses the error chain and returns the stack trace of the innermost error that has one. It returns nil if no error in the chain has a stack trace.
func (Callers) Format ¶
Format implements the fmt.Formatter interface.
Supported verbs:
- %s the complete stack trace, one frame per line
- %v same as %s; the '+' and '#' flags print the raw program counters
- %q the result of %s as a double-quoted Go string
func (Callers) Frames ¶
Frames returns a slice of Frame structs with function, file, and line information. It returns nil if the stack trace is empty.
func (Callers) String ¶
String implements the fmt.Stringer interface.
type DetailedError ¶
type DetailedError interface {
error
// ErrorDetails returns additional details about the error. It should not
// repeat the error message and should end with a newline.
//
// An empty string is returned if the error does not provide
// additional details.
ErrorDetails() string
}
DetailedError represents an error that provides additional details beyond the error message.
type Frame ¶
Frame represents a single stack frame with file, line, and function details.
func (Frame) Format ¶
Format implements the fmt.Formatter interface.
Supported verbs:
- %s function, file, and line number on a single line
- %f file path
- %d line number
- %n function name; the '+' flag prints the package path as well
- %v same as %s; the '+' and '#' flags print the struct fields
- %q the result of %s as a double-quoted Go string
type PanicError ¶ added in v1.0.0
PanicError represents an error that occurs during a panic. It is implemented by the errors returned by the Recover and FromRecover functions. It provides access to the original panic value via the Panic method.
Use the standard errors.As function to convert an error to this interface.