test

package
v6.0.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2021 License: Apache-2.0, BSD-2-Clause, BSD-3-Clause, + 1 more Imports: 5 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ColsFromStructByTag

func ColsFromStructByTag(tagName string, thing interface{}) []string

Extract the tag annotations from a struct into a string array

func SortErrors

func SortErrors(p []error) []error

SortErrors sorts the list of errors lexically

func SplitErrors

func SplitErrors(err error) []error

Types

type Error

type Error interface {
	Error() string
	Code() int
	Cause() error
	Prepend(string, ...interface{}) Error
}

Error describes an interface that supports error codes. It also allows for the first (causal) error to be easily referenced without needing to parse it. Adding error context is supported by prepending a string, and keeping the current error code.

usage:

func func1() Error {
	return test.NewError(404, "not found")
}

func func2() Error {
	err := func1()
	if err != nil {
		return err.Prepend("while in func2: ")
	}
}

func main() {
	err := func1()
	err.Code()  // 404
	err.Cause() // not found
}

func AddErrorCode

func AddErrorCode(code int, err error) Error

AddErrorCode takes an error and returns an instance satisfying the Error interface.

func NewError

func NewError(code int, fmtStr string, fmtArgs ...interface{}) Error

NewError constructs an error with a code.

type ErrorContext

type ErrorContext struct {
	// contains filtered or unexported fields
}

ErrorContext regulates which error codes can be made and keeps a count of all the errors created through the context.

`ErrorContext.NewError` can be used like `test.NewError` (see Error above) The primary difference is that the context prevents non-whitelisted error codes from being made.

Implementation details:

 contains a list of all valid error codes
	- allows user to make sure they are creating the correct errors
	- actually a map
		lookup can be done without linear search
		we can use the map to keep count of which errors are made
 contains mapping from error code to name/default message
	- not required for all error codes, or for any

An example setup:

package some_regex_checker

const (
	CommonBase            = 10 + iota
	NotEnoughAssignments
	BadAssignmentMatch
	...
)

// scoped to the package name
var ErrorContext *test.ErrorContext

func init() {
	errorCodes := []uint{
		NotEnoughAssignments,
		BadAssignmentMatch,
	}

	ErrorContext = test.NewErrorContext("cache config", errorCodes)
	err := ErrorContext.SetDefaultMessageForCode(NotEnoughAssignments, "not enough assignments in rule")
	// check err

	ErrorContext.TurnPanicOn()
}

func main() {
	// create a new user error with the context like this
	err := ErrorContext.NewError(BadAssignmentMatch, "bad assignment match")

	// there is no error code with 0, so this panics
	err = ErrorContext.NewError(0, "some error msg")
}

func NewErrorContext

func NewErrorContext(contextName string, errCodes []uint) *ErrorContext

NewErrorContext constructs an error context with list of valid codes.

func (*ErrorContext) AddDefaultErrorMessages

func (ec *ErrorContext) AddDefaultErrorMessages(mapping map[uint]string) error

AddDefaultMessages applies the SetDefaultMessageForCode function for every element in the given map. The function does not override the current contents of the map, everything is additive. An error is returned if a duplicate code is added.

parameter:

`mapping` is a map of error codes to their default error messages

func (ErrorContext) AddErrorCode

func (ec ErrorContext) AddErrorCode(code uint, err error) Error

AddErrorCode takes a regular error and gives it a code. Since this method is scoped to an error context, the code must exist in the whitelist.

func (ErrorContext) GetErrorStats

func (ec ErrorContext) GetErrorStats() map[uint]uint

GetErrorStats returns the map of error codes. usage:

stats := cxt.GetErrorStats()
stats[code] // represents the number of times an error with the code has been created

func (*ErrorContext) NewError

func (ec *ErrorContext) NewError(code uint, args ...interface{}) Error

NewError for an ErrorContext creates an error similar to test.NewError Any error created in this manner must have a code that belongs to the error context. The args is interpreted as a format string with args, but `...interface{}` is used because if no args are specified a lookup will be made to find the default configured string (see SetDefaultMessageForCode)

usage:

cxt.NewError(404, "not found: %v", prev_err)
cxt.NewError(404) // (default message must exist otherwise this is an error)

func (*ErrorContext) SetDefaultMessageForCode

func (ec *ErrorContext) SetDefaultMessageForCode(code uint, msg string) error

SetDefaultMessageForCode gives a default message for a given error code. Default messages must be configured before errors are created.

parameters:

`code` should exist in the error context, only one default message mapping can exist per error context
`msg` should be a plain string without special formatting

usage:

ErrorContext.SetDefaultMessageForCode(404, "not found")

// err has a default message
err := ErrorContext.NewError(404)

// the default message is overridden to add context to the error
err := ErrorContext.NewError(404, "not found: %v", prev_err")

func (*ErrorContext) TurnPanicOn

func (ec *ErrorContext) TurnPanicOn() error

TurnPanicOn enables panic mode.

When panic mode is on, ErrorContext methods that return errors will panic. Panic mode does not affect user-created errors. Panic mode can be used to assert the error context is set up correctly.

Although golang panics are highly discouraged, panic mode is made as an option. This decision was partially made because type assertions and map membership have similar options. If a user doesn't have panic mode on, they should still terminate after running into an error. Panic is off by default, and must be turned on explicitly so that the user must make an active decision. Panic must be turned on before errors are created.

Once turned on, panic mode can't be turned off.

type ErrorContextInternalErrorCode

type ErrorContextInternalErrorCode int
const (
	BadErrorCode  ErrorContextInternalErrorCode // when a bad error code is given in creation of new error
	BadDupMessage                               // when a default message already exists
	BadMsgLookup                                // when creating an error with no error message, default message wasn't found
	BadFmtString                                // when the fmt string isn't a string
	BadInitOrder                                // when the error context is modifed after having created an error
)

All internal errors for ErrorContext

Jump to

Keyboard shortcuts

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