errutil

package
v0.0.0-...-c6ea6ab Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2021 License: LGPL-3.0 Imports: 11 Imported by: 111

README

errutil

An error handling helper, providing more APIs than built-in package (errors, fmt), and compatible with go error interface

Why use errutil instead of built-in errors and fmt

Cover

Usage

  • Import package from master branch
import "github.com/tsaikd/KDGoLib/errutil"
  • Declare error factory
var ErrorOccurWithReason = errutil.NewFactory("An error occur, reason: %q")
  • Return error with factory
func doSomething() (err error) {
	// do something

	// return error with factory,
	// first argument is parent error,
	// the others are used for factory
	return ErrorOccurWithReason.New(nil, "some reason here")
}
  • Handle errors
func errorHandlingForOneCase() {
	if err := doSomething(); err != nil {
		if ErrorOccurWithReason.In(err) {
			// handling expected error
			return
		}

		// handling unexpected error
		return
	}
}
func errorHandlingForMultipleCases() {
	if err := doSomething(); err != nil {
		switch errutil.FactoryOf(err) {
		case ErrorOccurWithReason:
			// handling expected error
			return
		default:
			// handling unexpected error
			return
		}
	}
}

Optional usage

  • Import from v1 branch
import "gopkg.in/tsaikd/KDGoLib.v1/errutil"
  • Use like built-in errors package
    • bad case because all errors should be exported for catching by other package
func doSomething() (err error) {
	// do something

	// return error with factory
	return errutil.New("An error occur")
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultRuntimeCallerFilter = []runtimecaller.Filter{}

DefaultRuntimeCallerFilter use for filter error stack info

View Source
var (
	ErrorWalkLoop = NewFactory("detect error component parents loop when walking")
)

errors

Functions

func AddParent

func AddParent(errobj ErrorObject, parent ErrorObject) error

AddParent add parent to errobj

func AddRuntimeCallerFilter

func AddRuntimeCallerFilter(filters ...runtimecaller.Filter)

AddRuntimeCallerFilter add filters to DefaultRuntimeCallerFilter for RuntimeCaller()

func AllNamedFactories

func AllNamedFactories() map[string]ErrorFactory

AllNamedFactories return all named factories

func ContainErrorFunc

func ContainErrorFunc(err error, equalFunc func(error) bool) bool

ContainErrorFunc check error contain error by custom equalFunc

func Length

func Length(base ErrorObject) int

Length count number of ErrorObject and all parents, return -1 if error

func MarshalJSON

func MarshalJSON(errobj error) ([]byte, error)

MarshalJSON marshal error to json

func RuntimeCaller

func RuntimeCaller(skip int, extraFilters ...runtimecaller.Filter) (callinfo runtimecaller.CallInfo, ok bool)

RuntimeCaller wrap runtimecaller.GetByFilters() with DefaultRuntimeCallerFilter

func RuntimeCallerFilterStopErrutilPackage

func RuntimeCallerFilterStopErrutilPackage(callinfo runtimecaller.CallInfo) (valid bool, stop bool)

RuntimeCallerFilterStopErrutilPackage filter CallInfo to stop after reach KDGoLib/errutil package

func RuntimeCallerFilterStopSQLUtilPackage

func RuntimeCallerFilterStopSQLUtilPackage(callinfo runtimecaller.CallInfo) (valid bool, stop bool)

RuntimeCallerFilterStopSQLUtilPackage filter CallInfo to stop after reach KDGoLib/sqlutil package

func SetDefaultLogger

func SetDefaultLogger(logger LoggerType)

SetDefaultLogger set default LoggerType

func Trace

func Trace(errin error)

Trace error stack, output to default ErrorFormatter, panic if output error

func TraceSkip

func TraceSkip(errin error, skip int)

TraceSkip error stack, output to default ErrorFormatter, skip n function calls, panic if output error

func TraceWrap

func TraceWrap(errin error, wraperr error)

TraceWrap trace errin and wrap with wraperr only if errin != nil

func WalkErrors

func WalkErrors(base ErrorObject, walkFunc WalkFunc) (err error)

WalkErrors walk from base error through all parents return ErrorWalkLoop if detected loop

func WriteCallInfo

func WriteCallInfo(
	output io.Writer,
	callinfo runtimecaller.CallInfo,
	longFile bool,
	line bool,
	replacePackages map[string]string,
) (n int, err error)

WriteCallInfo write readable callinfo with options

Types

type ConsoleFormatter

type ConsoleFormatter struct {
	// seperator between errors, e.g. "; " will output "err1; err2; err3"
	Seperator string
	// output timestamp for prefix, e.g.  "2006-01-02 15:04:05 "
	TimeFormat string
	// show error position with long filename
	LongFile bool
	// show error position with short filename
	ShortFile bool
	// show error position with line number, work with LongFile or ShortFile
	Line bool
	// replace package name for securify
	ReplacePackages map[string]string
}

ConsoleFormatter used to format error object in console readable

func NewConsoleFormatter

func NewConsoleFormatter(seperator string) *ConsoleFormatter

NewConsoleFormatter create JSONErrorFormatter instance

func (*ConsoleFormatter) Format

func (t *ConsoleFormatter) Format(errin error) (errtext string, err error)

Format error object

func (*ConsoleFormatter) FormatSkip

func (t *ConsoleFormatter) FormatSkip(errin error, skip int) (errtext string, err error)

FormatSkip trace error line and format object

type ErrorFactory

type ErrorFactory interface {
	Error() string
	Name() string

	New(err error, params ...interface{}) ErrorObject
	Match(err error) bool
	In(err error) bool
}

ErrorFactory is used for create or check ErrorObject

func AllSortedNamedFactories

func AllSortedNamedFactories() []ErrorFactory

AllSortedNamedFactories return all sorted named factories NOTE: this is slow for sorting in runtime

func FactoryOf

func FactoryOf(err error) ErrorFactory

FactoryOf return factory of error, return nil if not factory found

func NewFactory

func NewFactory(errtext string) ErrorFactory

NewFactory return new ErrorFactory instance

func NewNamedFactory

func NewNamedFactory(name string, errtext string) ErrorFactory

NewNamedFactory return new ErrorFactory instance with factory name, panic if name duplicated

type ErrorFormatter

type ErrorFormatter interface {
	Format(error) (string, error)
}

ErrorFormatter to format error

type ErrorJSON

type ErrorJSON struct {
	ErrorPath      string          `json:"errorpath,omitempty"`
	ErrorMsg       string          `json:"error,omitempty"`
	ErrorMsgs      []string        `json:"errors,omitempty"`
	ErrorFactories map[string]bool `json:"errfac,omitempty"`
}

ErrorJSON is a helper struct for display error

func NewJSON

func NewJSON(err error) (*ErrorJSON, error)

NewJSON create ErrorJSON

func (*ErrorJSON) Error

func (t *ErrorJSON) Error() string

type ErrorObject

type ErrorObject interface {
	Error() string
	Factory() ErrorFactory
	Parent() ErrorObject
	SetParent(parent ErrorObject) ErrorObject
	runtimecaller.CallInfo
}

ErrorObject is a rich error interface

func New

func New(text string, errs ...error) ErrorObject

New return a new ErrorObject object

func NewErrors

func NewErrors(errs ...error) ErrorObject

NewErrors return ErrorObject that contains all input errors

func NewErrorsSkip

func NewErrorsSkip(skip int, errs ...error) ErrorObject

NewErrorsSkip return ErrorObject, skip function call

type JSONFormatter

type JSONFormatter struct{}

JSONFormatter used to format error to json

func NewJSONFormatter

func NewJSONFormatter() *JSONFormatter

NewJSONFormatter create JSONFormatter instance

func (*JSONFormatter) Format

func (t *JSONFormatter) Format(errin error) (errtext string, err error)

Format error to json

func (*JSONFormatter) FormatSkip

func (t *JSONFormatter) FormatSkip(errin error, skip int) (errtext string, err error)

FormatSkip trace error line and format to json

type LoggerOptions

type LoggerOptions struct {
	DefaultOutput   io.Writer
	ErrorOutput     io.Writer
	HideFile        bool
	ShortFile       bool
	HideLine        bool
	ReplacePackages map[string]string
	TraceFormatter  TraceFormatter
}

LoggerOptions for Logger

type LoggerType

type LoggerType interface {
	Debug(v ...interface{})
	Print(v ...interface{})
	Error(v ...interface{})
	Trace(errin error)
	TraceSkip(errin error, skip int)
}

LoggerType declare general log types

func Logger

func Logger() LoggerType

Logger return default LoggerType instance

func NewLogger

func NewLogger(opt LoggerOptions) LoggerType

NewLogger create LoggerType instance

type TraceFormatter

type TraceFormatter interface {
	ErrorFormatter
	FormatSkip(errin error, skip int) (string, error)
}

TraceFormatter to trace error occur line formatter

type WalkFunc

type WalkFunc func(errcomp ErrorObject) (stop bool, err error)

WalkFunc is a callback for WalkErrors

Jump to

Keyboard shortcuts

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