errors

package module
v0.1.10 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2022 License: Apache-2.0 Imports: 11 Imported by: 2

README

lipence/errors

Package errors provide stacktrace, chain and data field 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 interchangably with code that is expecting a normal error return.

Interface

Message is the basic message interface, all error objects implement this interface.

type Message interface {
	Code() string
	Message() string
}

Usage

Create and use an usual error object:

// an error object which implements `Message`
var Err0001 = errors.New(
	"e0001",          // code
	"internal error", // message
)

func doSomething() error {
    // something goes wrong
	if _, ok := someData["key"]; !ok {
	    return Err0001 // just return error
	}
	// ......
}

Wrap an error (explain why error happens):

error object (which implement golang error interface) could be wrapped with errors.Note and errors.Because.

errors.Because accepts current error object as cause, and receives Message as explaination.

errors.Note simply receives current error object to trace stack.

const FileMinLength = 10
var Err0001 = errors.New("e0001", "Can't read file")

func readSomething(path string) ([]byte, error) {
	if content, err := ioutil.ReadFile(path); err != nil {
		// return nil, errors.Note(Err0001)       // <= Just return Err0001
	    return nil, errors.Because(Err0001, err)  // <= Err0001's cause is err
	} else {
		return content, nil
	}
}

Annotate an error (collecting releated data):

errors.Note and errors.Because accepts dataFields as optional params. DataFields implements errors.Field, which is alias of zapcore.Field. Usage refers to field.go

var Err0002 = errors.New("e0002", "File is empty")

func readSomethingElse(path string) ([]byte, error) {
	if content, err := ioutil.ReadFile(path); err != nil {
		// reason and dataField
	    return nil, errors.Because(Err0001, err, errors.String("path", path))
	} else if len(content) < FileMinLength {
		// only dataFields
		return nil, errors.Note(Err0002, errors.String("path", path),
			errors.Int("length", len(content)),
			errors.Int("minLength", FileMinLength))
	} else {
		return content, nil
	}
}

Output Example

Console:

2021-12-17T01:52:37.357024+0800 ERROR   main.go:81  
open /tmp/a.txt: no such file or directory
e0001: Can't read file: {"path":"/tmp/a.txt"}
  [4] main.readSomethingElse
    example.com/test/err-test/main.go:50
  [3] main.processSomething
    example.com/test/err-test/main.go:62
e0003: Cant Process File
  [3] main.processSomething
    example.com/test/err-test/main.go:63
  [2] main.main
    example.com/test/err-test/main.go:69
  [1] runtime.main
    runtime/proc.go:225
  [0] runtime.goexit
    runtime/asm_arm64.s:1130

JSON:

[
    {
        "underlying": "open /tmp/a.txt: no such file or directory"
    },
    {
        "underlying": "e0001: Can't read file",
        "data": {
            "path": "/tmp/a.txt"
        },
        "stackTrace": [
            {
                "func": "[5] main.readSomethingElse",
                "line": "example.com/test/err-test/main.go:51"
            },
            {
                "func": "[4] main.processSomething",
                "line": "example.com/test/err-test/main.go:63"
            }
        ]
    },
    {
        "underlying": "e0003: Cant Process File",
        "stackTrace": [
            {
                "func": "[4] main.processSomething",
                "line": "example.com/test/err-test/main.go:64"
            },
            {
                "func": "[3] main.bootUp",
                "line": "example.com/test/err-test/main.go:82"
            },
            {
                "func": "[2] main.main",
                "line": "example.com/test/err-test/main.go:73"
            },
            {
                "func": "[1] runtime.main",
                "line": "runtime/proc.go:225"
            },
            {
                "func": "[0] runtime.goexit",
                "line": "runtime/asm_arm64.s:1130"
            }
        ]
    }
]

Changelog

  • v0.1.1 Built-in data fields Types and Factory
  • v0.1.0 First Release

Contact

Kenta Lee ( kenta.li@cardinfolink.com )

License

lipence/errors source code is available under the Apache-2.0 License

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AsJsonMarshaller added in v0.1.6

func AsJsonMarshaller(err error) error

func Batch added in v0.1.7

func Batch(errs []error) error

func Because

func Because(underlying *underlying, cause error, fields ...Field) error

func CausedBy

func CausedBy(src error, target error, deepFirst bool) bool

func CausedByNode

func CausedByNode(src error, target error, deepFirst bool, causeReceiver *error) (isCausedBy bool)

func Data

func Data(src error, key string, r bool) (interface{}, bool)

func From

func From(src interface{}) error

func HasData

func HasData(src error, key string, r bool) bool

func Is

func Is(err error, target error) bool

func New

func New(code, msg string) *underlying

func NewSysErr

func NewSysErr(message string) error

func NewSysErrf

func NewSysErrf(message string, args ...interface{}) error

func NewUnderlying

func NewUnderlying(code, message string) *underlying

func Note

func Note(err error, fields ...Field) error

func OnCreateMsg added in v0.1.3

func OnCreateMsg(filter MsgFilter)

func Unbatch added in v0.1.7

func Unbatch(errs error) ([]error, bool)

Types

type BatchErrors added in v0.1.7

type BatchErrors []error

func (BatchErrors) Error added in v0.1.7

func (e BatchErrors) Error() string

func (BatchErrors) MarshalJSON added in v0.1.7

func (e BatchErrors) MarshalJSON() ([]byte, error)

type ComparableErr

type ComparableErr interface {
	Is(error) bool
}

type Field

type Field = zapcore.Field

func Any

func Any(key string, value interface{}) Field

func Array

func Array(key string, val zapcore.ArrayMarshaler) Field

func Binary

func Binary(key string, val []byte) Field

func Bool

func Bool(key string, val bool) Field

func Boolp

func Boolp(key string, val *bool) Field

func Bools

func Bools(key string, bs []bool) Field

func ByteString

func ByteString(key string, val []byte) Field

func ByteStrings

func ByteStrings(key string, bss [][]byte) Field

func Complex128

func Complex128(key string, val complex128) Field

func Complex128p

func Complex128p(key string, val *complex128) Field

func Complex128s

func Complex128s(key string, nums []complex128) Field

func Complex64

func Complex64(key string, val complex64) Field

func Complex64p

func Complex64p(key string, val *complex64) Field

func Complex64s

func Complex64s(key string, nums []complex64) Field

func Duration

func Duration(key string, val time.Duration) Field

func Durationp

func Durationp(key string, val *time.Duration) Field

func Durations

func Durations(key string, ds []time.Duration) Field

func Error

func Error(err error) Field

func Errors

func Errors(key string, errs []error) Field

func Float32

func Float32(key string, val float32) Field

func Float32p

func Float32p(key string, val *float32) Field

func Float32s

func Float32s(key string, nums []float32) Field

func Float64

func Float64(key string, val float64) Field

func Float64p

func Float64p(key string, val *float64) Field

func Float64s

func Float64s(key string, nums []float64) Field

func Inline

func Inline(val zapcore.ObjectMarshaler) Field

func Int

func Int(key string, val int) Field

func Int16

func Int16(key string, val int16) Field

func Int16p

func Int16p(key string, val *int16) Field

func Int16s

func Int16s(key string, nums []int16) Field

func Int32

func Int32(key string, val int32) Field

func Int32p

func Int32p(key string, val *int32) Field

func Int32s

func Int32s(key string, nums []int32) Field

func Int64

func Int64(key string, val int64) Field

func Int64p

func Int64p(key string, val *int64) Field

func Int64s

func Int64s(key string, nums []int64) Field

func Int8

func Int8(key string, val int8) Field

func Int8p

func Int8p(key string, val *int8) Field

func Int8s

func Int8s(key string, nums []int8) Field

func Intp

func Intp(key string, val *int) Field

func Ints

func Ints(key string, nums []int) Field

func NamedError

func NamedError(key string, err error) Field

func Namespace

func Namespace(key string) Field

func Object

func Object(key string, val zapcore.ObjectMarshaler) Field

func Reflect

func Reflect(key string, val interface{}) Field

func Skip

func Skip() Field

func Stack

func Stack(key string) Field

func StackSkip

func StackSkip(key string, skip int) Field

func String

func String(key string, val string) Field

func Stringer

func Stringer(key string, val fmt.Stringer) Field

func Stringp

func Stringp(key string, val *string) Field

func Strings

func Strings(key string, ss []string) Field

func Time

func Time(key string, val time.Time) Field

func Timep

func Timep(key string, val *time.Time) Field

func Times

func Times(key string, ts []time.Time) Field

func Uint

func Uint(key string, val uint) Field

func Uint16

func Uint16(key string, val uint16) Field

func Uint16p

func Uint16p(key string, val *uint16) Field

func Uint16s

func Uint16s(key string, nums []uint16) Field

func Uint32

func Uint32(key string, val uint32) Field

func Uint32p

func Uint32p(key string, val *uint32) Field

func Uint32s

func Uint32s(key string, nums []uint32) Field

func Uint64

func Uint64(key string, val uint64) Field

func Uint64p

func Uint64p(key string, val *uint64) Field

func Uint64s

func Uint64s(key string, nums []uint64) Field

func Uint8

func Uint8(key string, val uint8) Field

func Uint8p

func Uint8p(key string, val *uint8) Field

func Uint8s

func Uint8s(key string, nums []uint8) Field

func Uintp

func Uintp(key string, val *uint) Field

func Uintptr

func Uintptr(key string, val uintptr) Field

func Uintptrp

func Uintptrp(key string, val *uintptr) Field

func Uintptrs

func Uintptrs(key string, us []uintptr) Field

func Uints

func Uints(key string, nums []uint) Field

type Message

type Message interface {
	Code() string
	Message() string
}

type MsgFilter added in v0.1.3

type MsgFilter func(code, msg string) (newCode, newMessage string)

type Tracer

type Tracer interface {
	Stack() []uintptr
}

Jump to

Keyboard shortcuts

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