errors

package module
v3.3.2 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2024 License: MIT Imports: 10 Imported by: 38

README

errors.v3

Go GitHub tag (latest SemVer) GoDoc Go Report Card Coverage Status FOSSA Status

Wrapped errors and more for golang developing (not just for go1.11, go1.13, and go1.20+).

hedzr/errors provides the compatibilities to your old project up to go 1.20.

hedzr/errors provides some extra enhancements for better context environment saving on error occurred.

Features

  • Simple migrating way from std errors: all of standard functions have been copied to
  • Better New():
  • Codes: treat a number as an error object
  • Unwrap inner canned errors one by one
  • No mental burden
Others

History

  • v3.3.1

    • fixed Iss() couldn't test the others except the first error.
  • v3.3.0

    • added Iss(err, errs...) to test if any of errors are included in 'err'.
    • improved As/Is/Unwrap to fit for new joint error since go1.20
    • added causes2.Clear, ...
    • improved Error() string
    • reviewed and re-published this repo from v3.3
  • v3.1.9

    • fixed error.Is deep test to check two errors' message text contents if matched
    • fixed errors.v3.Join when msg is not empty in an err obj
    • fixed causes.WithErrors(): err obj has been ignored even if its message is not empty
  • OLDER in CHANGELOG

Compatibilities

These features are supported for compatibilities.

stdlib `errors' compatibilities
  • func As(err error, target interface{}) bool
  • func Is(err, target error) bool
  • func New(text string) error
  • func Unwrap(err error) error
  • func Join(errs ...error) error
pkg/errors compatibilities
  • func Wrap(err error, message string) error
  • func Cause(err error) error: unwraps recursively, just like Unwrap()
  • func Cause1(err error) error: unwraps just one level
  • func WithCause(cause error, message string, args ...interface{}) error, = Wrap
  • supports Stacktrace
    • in an error by Wrap(), stacktrace wrapped;
    • for your error, attached by WithStack(cause error);
Some Enhancements
  • Iss(err error, errs ...error) bool
  • AsSlice(errs []error, target interface{}) bool
  • IsAnyOf(err error, targets ...error) bool
  • IsSlice(errs []error, target error) bool
  • TypeIs(err, target error) bool
  • TypeIsSlice(errs []error, target error) bool
  • Join(errs ...error) error
  • DumpStacksAsString(allRoutines bool) string
  • CanAttach(err interface{}) (ok bool)
  • CanCause(err interface{}) (ok bool)
  • CanCauses(err interface{}) (ok bool)
  • CanUnwrap(err interface{}) (ok bool)
  • CanIs(err interface{}) (ok bool)
  • CanAs(err interface{}) (ok bool)
  • Causes(err error) (errs []error)

Best Practices

Basics
package test

import (
    "gopkg.in/hedzr/errors.v3"
    "io"
    "reflect"
    "testing"
)

func TestForExample(t *testing.T) {
  fn := func() (err error) {
    ec := errors.New("some tips %v", "here")
    defer ec.Defer(&err)

    // attaches much more errors
    for _, e := range []error{io.EOF, io.ErrClosedPipe} {
      ec.Attach(e)
    }
  }

  err := fn()
  t.Logf("failed: %+v", err)

  // use another number different to default to skip the error frames
  err = errors.
        Skip(3). // from on Skip()
        WithMessage("some tips %v", "here").Build()
  t.Logf("failed: %+v", err)

  err = errors.
        Message("1"). // from Message() on
        WithSkip(0).
        WithMessage("bug msg").
        Build()
  t.Logf("failed: %+v", err)

  err = errors.
        NewBuilder(). // from NewBuilder() on
        WithCode(errors.Internal). // add errors.Code
        WithErrors(io.EOF). // attach inner errors
        WithErrors(io.ErrShortWrite, io.ErrClosedPipe).
        Build()
  t.Logf("failed: %+v", err)

  // As code
  var c1 errors.Code
  if errors.As(err, &c1) {
    println(c1) // = Internal
  }

  // As inner errors
  var a1 []error
  if errors.As(err, &a1) {
    println(len(a1)) // = 3, means [io.EOF, io.ErrShortWrite, io.ErrClosedPipe]
  }
  // Or use Causes() to extract them:
  if reflect.DeepEqual(a1, errors.Causes(err)) {
    t.Fatal("unexpected problem")
  }

  // As error, the first inner error will be extracted
  var ee1 error
  if errors.As(err, &ee1) {
    println(ee1) // = io.EOF
  }

  series := []error{io.EOF, io.ErrShortWrite, io.ErrClosedPipe, errors.Internal}
  var index int
  for ; ee1 != nil; index++ {
    ee1 = errors.Unwrap(err) // extract the inner errors one by one
    if ee1 != nil && ee1 != series[index] {
      t.Fatalf("%d. cannot extract '%v' error with As(), ee1 = %v", index, series[index], ee1)
    }
  }
}
Error Container (Inner/Nested)
func TestContainer(t *testing.T) {
  // as a inner errors container
  child := func() (err error) {
    ec := errors.New("multiple tasks have errors")
    defer ec.Defer(&err) // package the attached errors as a new one and return it as `err`

    for _, r := range []error{io.EOF, io.ErrShortWrite, io.ErrClosedPipe, errors.Internal} {
      ec.Attach(r)
    }
    
    doWithItem := func(item Item) (err error) {
      // ...
      return
    }
    for _, item := range SomeItems {
      // nil will be ignored safely, do'nt worry about invalid attaches.
      ec.Attach(doWithItem(item))
    }

    return
  }

  err := child() // get the canned errors as a packaged one
  t.Logf("failed: %+v", err)
}
Error Template

We could declare a message template at first and format it with live args to build an error instantly.

func TestErrorsTmpl(t *testing.T) {
  errTmpl := errors.New("expecting %v but got %v")

  var err error
  err = errTmpl.FormatWith("789", "123")
  t.Logf("The error is: %v", err)
  err = errTmpl.FormatWith(true, false)
  t.Logf("The error is: %v", err)
}

FormatWith will make new clone from errTmpl so you can use multiple cloned errors thread-safely.

The derived error instance is the descendant of the error template. This relation can be tested by errors.IsDescent(errTempl, err)

func TestIsDescended(t *testing.T) {
  err3 := New("any error tmpl with %v")
  err4 := err3.FormatWith("huahua")
  if !IsDescended(err3, err4) {
    t.Fatalf("bad test on IsDescended(err3, err4)")
  }
}
Better format for a nested error

Since v3.1.1, the better message format will be formatted at Printf("%+v").

func TestAs_betterFormat(t *testing.T) {
  var err = New("Have errors").WithErrors(io.EOF, io.ErrShortWrite, io.ErrNoProgress)
  t.Logf("%v\n", err)
  
  var nestNestErr = New("Errors FOUND:").WithErrors(err, io.EOF)
  var nnnErr = New("Nested Errors:").WithErrors(nestNestErr, strconv.ErrRange)
  t.Logf("%v\n", nnnErr)
  t.Logf("%+v\n", nnnErr)
}

The output is:

=== RUN   TestAs_betterFormat
    causes_test.go:23: Have errors [EOF | short write | multiple Read calls return no data or error]
    causes_test.go:27: Nested Errors: [Errors FOUND: [Have errors [EOF | short write | multiple Read calls return no data or error] | EOF] | value out of range]
    causes_test.go:28: Nested Errors:
          - Errors FOUND:
            - Have errors
              - EOF
              - short write
              - multiple Read calls return no data or error
            - EOF
          - value out of range
        
        gopkg.in/hedzr/errors%2ev3.TestAs_betterFormat
          /Volumes/VolHack/work/godev/cmdr-series/libs/errors/causes_test.go:26
        testing.tRunner
          /usr/local/go/src/testing/testing.go:1576
        runtime.goexit
          /usr/local/go/src/runtime/asm_amd64.s:1598
--- PASS: TestAs_betterFormat (0.00s)
PASS

LICENSE

MIT

Scan

FOSSA Status

Documentation

Overview

Package errors provides some error handling primitives for wrapped, coded, messaged errors.

Index

Constants

View Source
const (
	// AppName const
	AppName = "errors"
	// Version const
	Version = "3.3.2"
	// VersionInt const
	VersionInt = 0x030302
)

Variables

This section is empty.

Functions

func As

func As(err error, target interface{}) bool

As finds the first error in `err`'s chain that matches target, and if so, sets target to that error value and returns true.

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

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.

As will panic if target is not a non-nil pointer to either a type that implements error, or to any interface type. "As" returns false if err is nil.

func AsSlice

func AsSlice(errs []error, target interface{}) bool

AsSlice tests err.As for errs slice

func CanAs added in v3.0.3

func CanAs(err interface{}) (ok bool)

CanAs tests if err is as-able

func CanAttach added in v3.0.3

func CanAttach(err interface{}) (ok bool)

CanAttach tests if err is attach-able

func CanCause added in v3.0.3

func CanCause(err interface{}) (ok bool)

CanCause tests if err is cause-able

func CanCauses added in v3.0.5

func CanCauses(err interface{}) (ok bool)

CanCauses tests if err is cause-able

func CanIs added in v3.0.3

func CanIs(err interface{}) (ok bool)

CanIs tests if err is is-able

func CanUnwrap added in v3.0.3

func CanUnwrap(err interface{}) (ok bool)

CanUnwrap tests if err is unwrap-able

func Causes added in v3.0.5

func Causes(err error) (errs []error)

Causes simply returns the wrapped inner errors. It doesn't consider an wrapped Code entity is an inner error too. So if you wanna to extract any inner error objects, use errors.Unwrap for instead. The errors.Unwrap could extract all of them one by one:

var err = errors.New("hello").WithErrors(io.EOF, io.ShortBuffers)
var e error = err
for e != nil {
    e = errors.Unwrap(err)
}

func DumpStacksAsString added in v3.0.3

func DumpStacksAsString(allRoutines bool) string

DumpStacksAsString returns stack tracing information like debug.PrintStack()

func Is

func Is(err, target error) bool

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

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

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.

func IsAnyOf added in v3.0.23

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

IsAnyOf tests whether any of `targets` is in `err`.

func IsDescended added in v3.0.13

func IsDescended(ancestor, descendant error) bool

IsDescended test if ancestor is an error template and descendant is derived from it by calling ancestor.FormatWith.

func IsSlice

func IsSlice(errs []error, target error) bool

IsSlice tests err.Is for errs slice

func IsStd added in v3.3.0

func IsStd(err, target error) bool

func Iss added in v3.3.0

func Iss(err error, targets ...error) (matched bool)

func Join added in v3.1.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 errs contains no non-nil values. 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.

func NewLite added in v3.3.0

func NewLite(args ...interface{}) error

NewLite returns a simple message error object via stdlib (errors.New).

Sample:

var err1 = errors.New("message") // simple message
var err1 = errors.New(errors.WithStack(cause)) // return Error object with Opt

If no send any args as parameters, Code `UnsupportedOperation` returned.

func TypeIs

func TypeIs(err, target error) bool

TypeIs reports whether any error in `err`'s chain matches target.

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

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.

func TypeIsSlice

func TypeIsSlice(errs []error, target error) bool

TypeIsSlice tests err.Is for errs slice

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.

An errors.Error is an unwrappable error object, all its inner errors can be unwrapped in turn. Therefore it maintains an internal unwrapping index and it can't be reset externally. The only approach to clear it and make Unwrap work from head is, to keep Unwrap till this turn ending by returning nil.

Examples for Unwrap:

var err = errors.New("hello").WithErrors(io.EOF, io.ShortBuffers)
var e error = err
for e != nil {
    e = errors.Unwrap(err)
    // test if e is not nil and process it...
}

func WithStack

func WithStack(cause error) error

WithStack annotates err with a Stack trace at the point WithStack was called.

If err is nil, WithStack returns nil.

Types

type Attachable added in v3.0.5

type Attachable interface {
	// Attach collects the errors except it's nil
	//
	// StackTrace of errs will be copied to callee so that you can
	// get a trace output nearer by the last error.
	//
	Attach(errs ...error)
}

Attachable _

type Buildable added in v3.0.5

type Buildable interface {
	// error interface
	error

	// WithSkip specifies a special number of stack frames that will be ignored.
	WithSkip(skip int) Buildable
	// WithMessage formats the error message
	WithMessage(message string, args ...interface{}) Buildable //nolint:revive
	// WithCode specifies an error code.
	// An error code `Code` is a integer number with error interface
	// supported.
	WithCode(code Code) Buildable
	// WithErrors attaches the given errs as inner errors.
	//
	// WithErrors is like our old Attach().
	//
	// It wraps the inner errors into underlying container and
	// represents them all in a singular up-level error object.
	// The wrapped inner errors can be retrieved with errors.Causes:
	//
	//      var err = errors.New("hello").WithErrors(io.EOF, io.ShortBuffers)
	//      var errs []error = errors.Causes(err)
	//
	// Or, use As() to extract its:
	//
	//      var errs []error
	//      errors.As(err, &errs)
	//
	// Or, use Unwrap() for its:
	//
	//      var e error = err
	//      for e != nil {
	//          e = errors.Unwrap(err)
	//      }
	//
	// WithErrors attach child errors into an error container.
	// For a container which has IsEmpty() interface, it would not be
	// attached if it is empty (i.e. no errors).
	// For a nil error object, it will be ignored.
	WithErrors(errs ...error) Buildable
	// WithData appends errs if the general object is a error object.
	//
	// StackTrace of errs will be copied to callee so that you can get a
	// trace output nearer by the last error.
	//
	// defer-recover block typically is a better place of WithData().
	//
	// For example:
	//
	//    defer func() {
	//      if e := recover(); e != nil {
	//        err = errors.New("[recovered] copyTo unsatisfied ([%v] %v -> [%v] %v), causes: %v",
	//          c.indirectType(from.Type()), from, c.indirectType(to.Type()), to, e).
	//          WithData(e)                 // StackTrace of e -> err
	//        n := log.CalcStackFrames(1)   // skip defer-recover frame at first
	//        log.Skip(n).Errorf("%v", err) // skip go-lib frames and defer-recover frame, back to the point throwing panic
	//      }
	//    }()
	//
	WithData(errs ...interface{}) Buildable //nolint:revive
	// WithTaggedData appends user data with tag into internal container.
	// These data can be retrieved by
	WithTaggedData(siteScenes TaggedData) Buildable
	// WithCause sets the underlying error manually if necessary.
	WithCause(cause error) Buildable

	// WithMaxObjectStringLength set limitation for object stringify length.
	//
	// The objects of Data/TaggedData will be limited while its' been formatted with "%+v"
	WithMaxObjectStringLength(maxlen int) Buildable

	// End could terminate the with-build stream calls without any
	// returned value.
	End()

	// Container _
	Container

	// FormatWith create a new error based on an exists error template
	// with the given live args, the new error instance will be formatted.
	//
	// While you New an Error with format template without supplying
	// the args at same time, you'll create an error message template.
	// You could feed the live args later.
	// A sample is:
	//
	//    errTmpl := errors.New("template here: %v")
	//    // ...
	//    err = errTmpl.FormatWith("good day")
	//    println(err)   // got: template here: good day
	//    err = errTmpl.FormatWith("bye")
	//    println(err)   // got: template here: bye
	//
	FormatWith(args ...interface{}) error //nolint:revive
}

Buildable provides a fluent calling interface to make error building easy. Buildable is an error interface too.

type Builder

type Builder interface {
	// WithSkip specifies a special number of stack frames that will
	// be ignored.
	WithSkip(skip int) Builder
	// WithErrors attaches the given errs as inner errors.
	// For a container which has IsEmpty() interface, it would not
	// be attached if it is empty (i.e. no errors).
	// For a nil error object, it will be ignored.
	WithErrors(errs ...error) Builder
	// WithMessage formats the error message
	WithMessage(message string, args ...interface{}) Builder //nolint:revive
	// WithCode specifies an error code.
	WithCode(code Code) Builder

	// Build builds the final error object (with Buildable interface
	// bound)
	Build() Error
}

Builder provides a fluent calling interface to make error building easy.

func Message

func Message(message string, args ...interface{}) Builder

Message formats a message and starts a builder to create the final error object.

err := errors.Message("hello %v", "you").Attach(causer).Build()

func NewBuilder

func NewBuilder() Builder

NewBuilder starts a new error builder.

Typically, you could make an error with fluent calls:

err = errors.NewBuilder().
	WithCode(Internal).
	WithErrors(io.EOF).
	WithErrors(io.ErrShortWrite).
	Build()
t.Logf("failed: %+v", err)

func Skip

func Skip(skip int) Builder

Skip sets how many frames will be ignored while we are extracting the stacktrace info. Skip starts a builder with fluent API style, so you could continue build the error what you want:

err := errors.Skip(1).Message("hello %v", "you").Build()

type Code

type Code int32

A Code is a signed 32-bit error code copied from gRPC spec but negatived.

And more builtin error codes added since hedzr/errors.v3 (v3.1.6).

You may register any application-level error codes by calling RegisterCode(codeInt, desc).

const (
	// OK is returned on success. [HTTP/non-HTTP]
	OK Code = 0

	// Canceled indicates the operation was canceled (typically by the caller). [HTTP/non-HTTP]
	Canceled Code = -1

	// Unknown error. [HTTP/non-HTTP]
	// An example of where this error may be returned is
	// if a Status value received from another address space belongs to
	// an error-space that is not known in this address space. Also
	// errors raised by APIs that do not return enough error information
	// may be converted to this error.
	Unknown Code = -2

	// InvalidArgument indicates client specified an invalid argument. [HTTP]
	//
	// Note that this differs from FailedPrecondition. It indicates
	// arguments that are problematic regardless of the state of the
	// system (e.g., a malformed file name).
	//
	// And this also differs from IllegalArgument, who's applied and
	// identify an application error or a general logical error.
	InvalidArgument Code = -3

	// DeadlineExceeded means operation expired before completion. [HTTP]
	// For operations that change the state of the system, this error
	// might be returned even if the operation has completed
	// successfully. For example, a successful response from a server
	// could have been delayed long enough for the deadline to expire.
	//
	// = HTTP 408 Timeout
	DeadlineExceeded Code = -4

	// NotFound means some requested entity (e.g., file or directory)
	// wasn't found. [HTTP]
	//
	// = HTTP 404
	NotFound Code = -5

	// AlreadyExists means an attempt to create an entity failed
	// because one already exists. [HTTP]
	AlreadyExists Code = -6

	// PermissionDenied indicates the caller does not have permission to
	// execute the specified operation. [HTTP]
	//
	// It must not be used for rejections
	// caused by exhausting some resource (use ResourceExhausted
	// instead for those errors). It must not be
	// used if the caller cannot be identified (use Unauthenticated
	// instead for those errors).
	PermissionDenied Code = -7

	// ResourceExhausted indicates some resource has been exhausted,
	// perhaps a per-user quota, or perhaps the entire file system
	// is out of space. [HTTP]
	ResourceExhausted Code = -8

	// FailedPrecondition indicates operation was rejected because the
	// system is not in a state required for the operation's execution.
	// For example, directory to be deleted may be non-empty, a rmdir
	// operation is applied to a non-directory, etc. [HTTP]
	//
	// A litmus test that may help a service implementor in deciding
	// between FailedPrecondition, Aborted, and Unavailable:
	//  (a) Use Unavailable if the client can retry just the failing call.
	//  (b) Use Aborted if the client should retry at a higher-level
	//      (e.g., restarting a read-modify-write sequence).
	//  (c) Use FailedPrecondition if the client should not retry until
	//      the system state has been explicitly fixed. E.g., if a "rmdir"
	//      fails because the directory is non-empty, FailedPrecondition
	//      should be returned since the client should not retry unless
	//      they have first fixed up the directory by deleting files from it.
	//  (d) Use FailedPrecondition if the client performs conditional
	//      REST Get/Update/Delete on a resource and the resource on the
	//      server does not match the condition. E.g., conflicting
	//      read-modify-write on the same resource.
	FailedPrecondition Code = -9

	// Aborted indicates the operation was aborted, typically due to a
	// concurrency issue like sequencer check failures, transaction aborts,
	// etc. [HTTP]
	//
	// See litmus test above for deciding between FailedPrecondition,
	// Aborted, and Unavailable.
	Aborted Code = -10

	// OutOfRange means operation was attempted past the valid range. [HTTP]
	//
	// E.g., seeking or reading past end of file.
	//
	// Unlike InvalidArgument, this error indicates a problem that may
	// be fixed if the system state changes. For example, a 32-bit file
	// system will generate InvalidArgument if asked to read at an
	// offset that is not in the range [0,2^32-1], but it will generate
	// OutOfRange if asked to read from an offset past the current
	// file size.
	//
	// There is a fair bit of overlap between FailedPrecondition and
	// OutOfRange. We recommend using OutOfRange (the more specific
	// error) when it applies so that callers who are iterating through
	// a space can easily look for an OutOfRange error to detect when
	// they are done.
	OutOfRange Code = -11

	// Unimplemented indicates operation is not implemented or not
	// supported/enabled in this service. [HTTP]
	Unimplemented Code = -12

	// Internal errors [HTTP].
	//
	// Means some invariants expected by underlying
	// system has been broken. If you see one of these errors,
	// something is very broken.
	Internal Code = -13

	// Unavailable indicates the service is currently unavailable. [HTTP]
	// This is a most likely a transient condition and may be corrected
	// by retrying with a backoff. Note that it is not always safe to
	// retry non-idempotent operations.
	//
	// See litmus test above for deciding between FailedPrecondition,
	// Aborted, and Unavailable.
	Unavailable Code = -14

	// DataLoss indicates unrecoverable data loss or corruption. [HTTP]
	DataLoss Code = -15

	// Unauthenticated indicates the request does not have valid
	// authentication credentials for the operation. [HTTP]
	//
	// = HTTP 401 Unauthorized
	Unauthenticated Code = -16

	// RateLimited indicates some flow control algorithm is running. [HTTP]
	// and applied.
	//
	// = HTTP Code 429
	RateLimited Code = -17

	// BadRequest generates a 400 error. [HTTP]
	//
	// = HTTP 400
	BadRequest Code = -18

	// Conflict generates a 409 error. [HTTP]
	//
	// = hTTP 409
	Conflict Code = -19

	// Forbidden generates a 403 error. [HTTP]
	Forbidden Code = -20

	// InternalServerError generates a 500 error. [HTTP]
	InternalServerError Code = -21

	// MethodNotAllowed generates a 405 error. [HTTP]
	MethodNotAllowed Code = -22

	// Timeout generates a Timeout error.
	Timeout Code = -23

	// IllegalState is used for the application is entering a
	// bad state.
	IllegalState Code = -24

	// IllegalFormat can be used for Format failed, user input parsing
	// or analysis failed, etc.
	IllegalFormat Code = -25

	// IllegalArgument is like InvalidArgument but applied on application.
	IllegalArgument Code = -26

	// InitializationFailed is used for application start up unsuccessfully.
	InitializationFailed Code = -27

	// DataUnavailable is used for the data fetching failed.
	DataUnavailable Code = -28

	// UnsupportedOperation is like MethodNotAllowed but applied on application.
	UnsupportedOperation Code = -29

	// UnsupportedVersion can be used for production continuously iteration.
	UnsupportedVersion Code = -30

	// MinErrorCode is the lower bound for user-defined Code.
	MinErrorCode Code = -1000
)

func RegisterCode added in v3.0.21

func RegisterCode(codePositive int, codeName string) (errno Code)

RegisterCode makes a code integer associated with a name, and returns the available Code number.

When a positive integer given as codePositive (such as 3), it'll be negatived and added errors.MinErrorCode (-1000) so the final Code number will be -1003.

When a negative integer given, and it's less than errors.MinErrorCode, it'll be used as it. Or an errors.AlreadyExists returned.

An existing code will be returned directly.

RegisterCode provides a shortcut to declare a number as Code as your need.

The best way is:

var ErrAck = errors.RegisterCode(3, "cannot ack")     // ErrAck will be -1003
var ErrAck = errors.RegisterCode(-1003, "cannot ack)  // equivalent with last line

func (Code) Error

func (c Code) Error() string

Error for error interface

func (Code) Format added in v3.1.6

func (c Code) Format(s fmt.State, verb rune)

Format formats the stack of Frames according to the fmt.Formatter interface.

%s	lists source files for each Frame in the stack
%v	lists the source file and line number for each Frame in the stack

Format accepts flags that alter the printing of some verbs, as follows:

%+v   Prints filename, function, and line number for each Frame in the stack.

func (Code) Is added in v3.3.0

func (c Code) Is(other error) bool

func (Code) New

func (c Code) New(msg string, args ...interface{}) Buildable

New create a new *CodedErr object based an error code

func (Code) Register

func (c Code) Register(codeName string) (errno Code)

Register registers a code and its token string for using later

func (Code) String

func (c Code) String() string

String for stringer interface

func (*Code) WithCode

func (c *Code) WithCode(code Code) *Code

WithCode for error interface

type Container added in v3.0.5

type Container interface {
	// IsEmpty returns true if Error is an error container which holded any inner errors.
	//
	// IsEmpty tests if it has any attached errors
	IsEmpty() bool
	// Defer can be used as a defer function to simplify your codes.
	//
	// The codes:
	//
	//     func some(){
	//       // as a inner errors container
	//       child := func() (err error) {
	//      	errContainer := errors.New("")
	//      	defer errContainer.Defer(&err)
	//
	//      	for _, r := range []error{io.EOF, io.ErrClosedPipe, errors.Internal} {
	//      		errContainer.Attach(r)
	//      	}
	//
	//      	return
	//       }
	//
	//       err := child()
	//       t.Logf("failed: %+v", err)
	//    }
	//
	Defer(err *error)
	Clear() Container // clear all nested errors, internal states
	// Attachable _
	Attachable
}

Container represents an error container which can hold a group of inner errors.

type Error added in v3.0.5

type Error interface {
	// Buildable _
	Buildable

	// Data returns the wrapped common user data by Buildable.WithData.
	//
	// The error objects with a passed Buildable.WithData will be moved
	// into inner errors set, so its are excluded from Data().
	Data() []interface{} //nolint:revive
	// TaggedData returns the wrapped tagged user data by
	// Buildable.WithTaggedData.
	TaggedData() TaggedData
	// Cause returns the underlying cause of the error, if possible.
	// An error value has a cause if it implements the following
	// interface:
	//
	//     type causer interface {
	//            Cause() error
	//     }
	//
	// If an error object does not implement Cause interface, the
	// original error object will be returned.
	// If the error is nil, nil will be returned without further
	// investigation.
	Cause() error
	// Causes simply returns the wrapped inner errors.
	// It doesn't consider an wrapped Code entity is an inner error too.
	// So if you wanna to extract any inner error objects, use
	// errors.Unwrap for instead. The errors.Unwrap could extract all
	// of them one by one:
	//
	//      var err = errors.New("hello").WithErrors(io.EOF, io.ShortBuffers)
	//      var e error = err
	//      for e != nil {
	//          e = errors.Unwrap(err)
	//      }
	//
	Causes() []error
}

Error object

func New

func New(args ...interface{}) Error

New returns an error with the supplied message. New also records the Stack trace at the point where it was called.

New supports two kind of args: an Opt option or a message format with variadic args.

Sample 1:

var err = errors.New("message here: %s", "hello")

Sample 2:

var err = errors.New(errors.WithErrors(errs...))
var err = errors.New(errors.WithStack(cause))

Sample 3:

var err = errors.New().WithErrors(errs...)

type Frame

type Frame uintptr

Frame represents a program counter inside a Stack frame.

func (Frame) Format

func (f Frame) Format(s fmt.State, verb rune)

Format formats the frame according to the fmt.Formatter interface.

%s    source file
%d    source line
%n    function name
%v    equivalent to %s:%d

Format accepts flags that alter the printing of some verbs, as follows:

%+s   function name and path of source file relative to the
      compiling time.
      GOPATH separated by \n\t (<funcname>\n\t<path>)
%+v   equivalent to %+s:%d

type Opt

type Opt func(s *builder)

Opt _

func WithErrors

func WithErrors(errs ...error) Opt

WithErrors attach child errors into an error container. For a container which has IsEmpty() interface, it would not be attached if it is empty (i.e. no errors). For a nil error object, it will be ignored.

Sample:

err := errors.New(errors.WithErrors(errs...))

type Stack

type Stack []uintptr

Stack represents a Stack of program counters.

func (*Stack) Format

func (s *Stack) Format(st fmt.State, verb rune)

Format formats the stack of Frames according to the fmt.Formatter interface.

%s	lists source files for each Frame in the stack
%v	lists the source file and line number for each Frame in the stack

Format accepts flags that alter the printing of some verbs, as follows:

%+v   Prints filename, function, and line number for each Frame in the stack.

func (*Stack) StackTrace

func (s *Stack) StackTrace() StackTrace

StackTrace returns the stacktrace frames

type StackTrace

type StackTrace []Frame

StackTrace is Stack of Frames from innermost (newest) to outermost (oldest).

func (StackTrace) Format

func (st StackTrace) Format(s fmt.State, verb rune)

Format formats the Stack of Frames according to the fmt.Formatter interface.

%s	lists source files for each Frame in the Stack
%v	lists the source file and line number for each Frame in the Stack

Format accepts flags that alter the printing of some verbs, as follows:

%+v   Prints filename, function, and line number for each Frame in the Stack.

type TaggedData

type TaggedData map[string]interface{} //nolint:revive

TaggedData _

type WithStackInfo

type WithStackInfo struct {
	*Stack
	// contains filtered or unexported fields
}

WithStackInfo is exported now

func Wrap

func Wrap(err error, message string, args ...interface{}) *WithStackInfo

Wrap returns an error annotating err with a Stack trace at the point Wrap is called, and the supplied message. If err is nil, Wrap returns nil.

func (*WithStackInfo) As

func (w *WithStackInfo) As(target interface{}) bool

As finds the first error in `err`'s chain that matches target, and if so, sets target to that error value and returns true.

func (*WithStackInfo) Attach

func (w *WithStackInfo) Attach(errs ...error)

Attach collects the errors except an error is nil.

StackTrace of errs will be copied to callee so that you can get a trace output nearer by the last error.

Since v3.0.5, we break Attach() and remove its returning value. So WithStackInfo is a Container compliant type now.

func (*WithStackInfo) Cause

func (w *WithStackInfo) Cause() error

Cause returns the underlying cause of the error, if possible. An error value has a cause if it implements the following interface:

type causer interface {
       Cause() error
}

If an error object does not implement Cause interface, the original error object will be returned. If the error is nil, nil will be returned without further investigation.

func (*WithStackInfo) Causes

func (w *WithStackInfo) Causes() []error

Causes simply returns the wrapped inner errors. It doesn't consider an wrapped Code entity is an inner error too. So if you wanna to extract any inner error objects, use errors.Unwrap for instead. The errors.Unwrap could extract all of them one by one:

var err = errors.New("hello").WithErrors(io.EOF, io.ShortBuffers)
var e error = err
for e != nil {
    e = errors.Unwrap(err)
}

func (*WithStackInfo) Clear added in v3.3.0

func (w *WithStackInfo) Clear() Container

func (*WithStackInfo) Clone added in v3.0.11

func (w *WithStackInfo) Clone() *WithStackInfo

Clone _

func (*WithStackInfo) Data added in v3.0.5

func (w *WithStackInfo) Data() []interface{}

Data returns the wrapped common user data by WithData. The error objects with passed WithData will be moved into inner errors set, so its are excluded from Data().

func (*WithStackInfo) Defer

func (w *WithStackInfo) Defer(err *error)

Defer can be used as a defer function to simplify your codes.

The codes:

 func some(){
   // as a inner errors container
   child := func() (err error) {
  	errContainer := errors.New("")
  	defer errContainer.Defer(&err)

  	for _, r := range []error{io.EOF, io.ErrClosedPipe, errors.Internal} {
  		errContainer.Attach(r)
  	}

  	return
   }

   err := child()
   t.Logf("failed: %+v", err)
}

func (*WithStackInfo) End

func (w *WithStackInfo) End()

End ends the WithXXX stream calls while you dislike unwanted `err =`.

For instance, the construction of an error without warnings looks like:

err := New("hello %v", "world")
_ = err.
    WithErrors(io.EOF, io.ErrShortWrite).
    WithErrors(io.ErrClosedPipe).
    WithCode(Internal)

To avoid the `_ =`, you might beloved with a End() call:

err := New("hello %v", "world")
err.WithErrors(io.EOF, io.ErrShortWrite).
    WithErrors(io.ErrClosedPipe).
    WithCode(Internal).
    End()

func (*WithStackInfo) Error

func (w *WithStackInfo) Error() string

func (*WithStackInfo) Format

func (w *WithStackInfo) Format(s fmt.State, verb rune)

Format formats the stack of Frames according to the fmt.Formatter interface.

%s   lists source files for each Frame in the stack
%v   lists the source file and line number for each Frame in the stack

Format accepts flags that alter the printing of some verbs, as follows:

%+v   Prints filename, function, and line number for each Frame in the stack.

func (*WithStackInfo) FormatWith added in v3.0.8

func (w *WithStackInfo) FormatWith(args ...interface{}) error

FormatWith _

func (*WithStackInfo) Is

func (w *WithStackInfo) Is(target error) bool

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

func (*WithStackInfo) IsDescended added in v3.0.13

func (w *WithStackInfo) IsDescended(descendant error) bool

func (*WithStackInfo) IsEmpty

func (w *WithStackInfo) IsEmpty() bool

IsEmpty tests has attached errors

func (*WithStackInfo) Reset added in v3.0.5

func (w *WithStackInfo) Reset()

func (*WithStackInfo) String added in v3.1.1

func (w *WithStackInfo) String() string

String for stringer interface

func (*WithStackInfo) TaggedData added in v3.0.5

func (w *WithStackInfo) TaggedData() TaggedData

TaggedData returns the wrapped tagged user data by WithTaggedData.

func (*WithStackInfo) TypeIs

func (w *WithStackInfo) TypeIs(target error) bool

func (*WithStackInfo) Unwrap

func (w *WithStackInfo) Unwrap() error

func (*WithStackInfo) WithCause

func (w *WithStackInfo) WithCause(cause error) Buildable

WithCause sets the underlying error manually if necessary.

func (*WithStackInfo) WithCode

func (w *WithStackInfo) WithCode(code Code) Buildable

WithCode specifies an error code. An error code `Code` is a integer number with error interface supported.

func (*WithStackInfo) WithData

func (w *WithStackInfo) WithData(errs ...interface{}) Buildable

WithData appends errs if the general object is a error object.

StackTrace of errs will be copied to callee so that you can get a trace output nearer by the last error.

defer-recover block typically is a better place of WithData().

For example:

defer func() {
  if e := recover(); e != nil {
    err = errors.New("[recovered] copyTo unsatisfied ([%v] %v -> [%v] %v), causes: %v",
      c.indirectType(from.Type()), from, c.indirectType(to.Type()), to, e).
      WithData(e)                 // StackTrace of e -> err
    n := log.CalcStackFrames(1)   // skip defer-recover frame at first
    log.Skip(n).Errorf("%v", err) // skip go-lib frames and defer-recover frame, back to the point throwing panic
  }
}()

func (*WithStackInfo) WithErrors

func (w *WithStackInfo) WithErrors(errs ...error) Buildable

WithErrors attaches the given errs as inner errors.

WithErrors is similar with Attach() except it collects thees errors:

1. For an error implemented IsEmpty(), only if it is not empty (i.e. IsEmpty() return false). So the inner errors within an error container will be moved out from that container, and be copied into this holder.

2. For a normal error, such as io.EOF, just add it.

It wraps the inner errors into underlying container and represents them all in a singular up-level error object. The wrapped inner errors can be retrieved with errors.Causes:

var err = errors.New("hello").WithErrors(io.EOF, io.ShortBuffers)
var errs []error = errors.Causes(err)

Or, use As() to extract its:

var errs []error
errors.As(err, &errs)

func (*WithStackInfo) WithMaxObjectStringLength added in v3.1.5

func (w *WithStackInfo) WithMaxObjectStringLength(maxlen int) Buildable

WithMaxObjectStringLength set limitation for object stringify length.

The objects of Data/TaggedData will be limited while its' been formatted with "%+v"

func (*WithStackInfo) WithMessage

func (w *WithStackInfo) WithMessage(message string, args ...interface{}) Buildable

WithMessage formats the error message

func (*WithStackInfo) WithSkip

func (w *WithStackInfo) WithSkip(skip int) Buildable

WithSkip specifies a special number of stack frames that will be ignored.

func (*WithStackInfo) WithTaggedData

func (w *WithStackInfo) WithTaggedData(siteScenes TaggedData) Buildable

WithTaggedData appends errs if the general object is a error object

Jump to

Keyboard shortcuts

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