errors

package module
v0.0.0-...-b2843c2 Latest Latest
Warning

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

Go to latest
Published: May 11, 2022 License: Apache-2.0 Imports: 6 Imported by: 0

README

errors

Go Report Card GoDoc

This go package provides error handling primitives based on error codes.

Introduction

Error coding is an ancient method of error orchestration. It's not elegant, but it works. When errors have codes, they are easy to transport, tag, locate, and classify. It would be more conducive to aspect oriented programming.

Usage

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

Sentinel Error

Declare sentinel errors with constants to avoid tampering.

const (
	ErrNotFoundOrders = errors.ConstError("[NF_BIS_Order] Not found orders")
	ErrDbAccessDeny   = errors.ConstError("[AD_TEC_DbConnect] Database access denied")
)

Adding context to an error

The errors.Wrap function returns a new error that adds context to the original error. For example

_, err := ioutil.ReadAll(r)
if err != nil {
        return errors.Wrap(err, "IO_TEC_ReadFile", "read failed")
}

Handling errors

You can easily handle different types of errors without identifying the source of the error.

// Assume that access denied errors codes start with "AD_"
if errors.Match(err, regexp.MustCompile("^AD_.*$")) {
	// Handling access denied errors
}

Documentation

Index

Examples

Constants

This section is empty.

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. Otherwise, it returns false.

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.

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.

func ErrCode

func ErrCode(code, message string) error

ErrCode returns an error with error code and message.

func ErrCodef

func ErrCodef(code, format string, args ...interface{}) error

ErrCodef returns an error with an error code and a message that is formatted according to the format specifier.

func Errorf

func Errorf(format string, args ...interface{}) error

Errorf formats according to a format specifier and returns the string as a value that satisfies error. If a string begins with code enclosed in [], that code is considered an error code.

func GetCode

func GetCode(err error) (string, bool)

GetCode finds the first error in err's chain that implements a method Code() string, and if so, returns the code extracted from error and the boolean is true. Otherwise the returned value will be empty and the boolean will be false.

func HasStackTrace

func HasStackTrace(err error) bool

HasStackTrace reports whether has call stack information in err's chain.

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.

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.

func Match

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

Match reports whether any error in err's chain matches key.

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

An error if it implements a method Match(key) bool such that Match(target) returns true.

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

func (m MyError) Match(key interface{}) bool {
  return m.code == key
}

then Match(MyError{code:"ERR001"}, "ERR001") returns true.

func New

func New(message string) error

New returns an error with the supplied message. If a message begins with code enclosed in [], that code is considered an error code.

Example
package main

import (
	"fmt"

	"github.com/nextf/errors"
)

func main() {
	err := errors.ErrCode("ERR001", "whoops")
	fmt.Println(err)
}
Output:

[ERR001] whoops
Example (Printf1)
package main

import (
	"fmt"

	"github.com/nextf/errors"
)

func main() {
	err := errors.ErrCode("ERR001", "whoops")
	// err2 := errors.WithStack(err)
	fmt.Printf("%s\n", err)
	fmt.Printf("%v\n", err)
	// fmt.Printf("%+v\n", err2)
	
Example (Printf2)
package main

import (
	"fmt"

	"github.com/nextf/errors"
)

func main() {
	err := errors.TraceableErrCode("ERR001", "whoops")
	fmt.Printf("%+4v", err)
}
Output:

[ERR001] whoops
Caused by: @callstack
    github.com/nextf/errors_test.ExampleNew_printf2(example_test.go:29)
    testing.runExample(run_example.go:64)
    testing.runExamples(example.go:44)
    testing.(*M).Run(testing.go:1505)
    ...(more:3)

func Trace

func Trace(err error) error

Trace annotates err with a call stack information at the point Trace was called. If err is nil, Trace returns nil.

func TraceMessage deprecated

func TraceMessage(err error, message string) error

Deprecated: Too simple. Use errors.Wrap instead.

func TraceMessagef deprecated

func TraceMessagef(err error, format string, args ...interface{}) error

Deprecated: Too simple. Use errors.Wrapf instead.

func TraceNodup

func TraceNodup(err error) error

Trace annotates err with a call stack information at the point Trace was called. If the err already contains call stack information, Trace returns the err itself. If err is nil, Trace returns nil.

func TraceableErrCode

func TraceableErrCode(code, message string) error

TraceableErrCode returns an error with call stack information and error code and message.

func TraceableErrCodef

func TraceableErrCodef(code, format string, args ...interface{}) error

TraceableErrCodef returns an error with call stack information and error code and a message formatted according to the format specifier.

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.

func WithErrCode

func WithErrCode(err error, code, message string) error

WithErrCode annotates err with an error code and message. If err is nil, WithErrCode returns nil.

Example
package main

import (
	"fmt"
	"os"

	"github.com/nextf/errors"
)

func openNotExistsFile() (*os.File, error) {
	f, err := os.Open("/not_exists_file.txt")
	if err != nil {
		return nil, errors.WithErrCode(err, "ERR404", "File not found")
	}
	return f, nil
}
func main() {
	_, err := openNotExistsFile()
	fmt.Printf("%+v", err)
}
Output:

[ERR404] File not found
Caused by: open /not_exists_file.txt: The system cannot find the file specified.

func WithErrCodef

func WithErrCodef(err error, code, format string, args ...interface{}) error

WithErrCode annotates err with an error code and a message that is formatted according to the format specifier. If err is nil, WithErrCode returns nil.

func Wrap

func Wrap(err error, code, message string) error

Wrap returns an error annotating err with a call stack information at the point Wrap was called, and an error code and message. If err is nil, Wrap returns nil.

Example
package main

import (
	"fmt"
	"os"

	"github.com/nextf/errors"
)

func openNotExistsFile2() (*os.File, error) {
	f, err := os.Open("/not_exists_file.txt")
	if err != nil {
		return nil, errors.WrapNodup(err, "ERR404", "File not found")
	}
	return f, nil
}

func main() {
	_, err := openNotExistsFile2()
	fmt.Printf("%+5v", err)
}
Output:

[ERR404] File not found
Caused by: @callstack
    github.com/nextf/errors_test.openNotExistsFile2(example_test.go:59)
    github.com/nextf/errors_test.ExampleWrap(example_test.go:65)
    testing.runExample(run_example.go:64)
    testing.runExamples(example.go:44)
    testing.(*M).Run(testing.go:1505)
    ...(more:3)
Caused by: open /not_exists_file.txt: The system cannot find the file specified.

func WrapNodup

func WrapNodup(err error, code, message string) error

WrapNodup returns an error annotating err with a call stack information at the point WrapNodup was called, and an error code and message. If the err already contains call stack information, than annotation is not repeated. If err is nil, WrapNodup returns nil.

func WrapNodupf

func WrapNodupf(err error, code, format string, args ...interface{}) error

WrapNodupf returns an error annotating err with a call stack information at the point WrapNodupf was called, and an error code and a message that is formatted according to the format specifier. If the err already contains call stack information, than annotation is not repeated. If err is nil, WrapNodupf returns nil.

func Wrapf

func Wrapf(err error, code, format string, args ...interface{}) error

Wrapf returns an error annotating err with a call stack information at the point Wrapf was called, and an error code and a message that is formatted according to the format specifier. If err is nil, Wrapf returns nil.

Types

type ConstError

type ConstError string

func (ConstError) Code

func (e ConstError) Code() string

func (ConstError) Error

func (e ConstError) Error() string

func (ConstError) Match

func (e ConstError) Match(key interface{}) bool

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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