exerr

package
v0.0.444 Latest Latest
Warning

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

Go to latest
Published: May 3, 2024 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MDTString      metaDataType = "String"
	MDTStringPtr   metaDataType = "StringPtr"
	MDTInt         metaDataType = "Int"
	MDTInt8        metaDataType = "Int8"
	MDTInt16       metaDataType = "Int16"
	MDTInt32       metaDataType = "Int32"
	MDTInt64       metaDataType = "Int64"
	MDTFloat32     metaDataType = "Float32"
	MDTFloat64     metaDataType = "Float64"
	MDTBool        metaDataType = "Bool"
	MDTBytes       metaDataType = "Bytes"
	MDTObjectID    metaDataType = "ObjectID"
	MDTTime        metaDataType = "Time"
	MDTDuration    metaDataType = "Duration"
	MDTStringArray metaDataType = "StringArr"
	MDTIntArray    metaDataType = "IntArr"
	MDTInt32Array  metaDataType = "Int32Arr"
	MDTID          metaDataType = "ID"
	MDTAny         metaDataType = "Interface"
	MDTNil         metaDataType = "Nil"
	MDTEnum        metaDataType = "Enum"
)

Variables

View Source
var (
	CatWrap    = ErrorCategory{"Wrap"}    // The error is simply wrapping another error (e.g. when a grpc call returns an error)
	CatSystem  = ErrorCategory{"System"}  // An internal system error (e.g. connection to db failed)
	CatUser    = ErrorCategory{"User"}    // The user (the API caller) did something wrong (e.g. he has no permissions to do this)
	CatForeign = ErrorCategory{"Foreign"} // A foreign error that some component threw (e.g. an unknown mongodb error), happens if we call Wrap(..) on an non-bmerror value
)
View Source
var (
	SevTrace = ErrorSeverity{"Trace"}
	SevDebug = ErrorSeverity{"Debug"}
	SevInfo  = ErrorSeverity{"Info"}
	SevWarn  = ErrorSeverity{"Warn"}
	SevErr   = ErrorSeverity{"Err"}
	SevFatal = ErrorSeverity{"Fatal"}
)
View Source
var (
	TypeInternal       = NewType("INTERNAL_ERROR", langext.Ptr(500))
	TypePanic          = NewType("PANIC", langext.Ptr(500))
	TypeNotImplemented = NewType("NOT_IMPLEMENTED", langext.Ptr(500))

	TypeMongoQuery        = NewType("MONGO_QUERY", langext.Ptr(500))
	TypeCursorTokenDecode = NewType("CURSOR_TOKEN_DECODE", langext.Ptr(500))
	TypeMongoFilter       = NewType("MONGO_FILTER", langext.Ptr(500))
	TypeMongoReflection   = NewType("MONGO_REFLECTION", langext.Ptr(500))
	TypeMongoInvalidOpt   = NewType("MONGO_INVALIDOPT", langext.Ptr(500))

	TypeSQLQuery  = NewType("SQL_QUERY", langext.Ptr(500))
	TypeSQLBuild  = NewType("SQL_BUILD", langext.Ptr(500))
	TypeSQLDecode = NewType("SQL_DECODE", langext.Ptr(500))

	TypeWrap = NewType("Wrap", nil)

	TypeBindFailURI      = NewType("BINDFAIL_URI", langext.Ptr(400))
	TypeBindFailQuery    = NewType("BINDFAIL_QUERY", langext.Ptr(400))
	TypeBindFailJSON     = NewType("BINDFAIL_JSON", langext.Ptr(400))
	TypeBindFailFormData = NewType("BINDFAIL_FORMDATA", langext.Ptr(400))
	TypeBindFailHeader   = NewType("BINDFAIL_HEADER", langext.Ptr(400))

	TypeMarshalEntityID = NewType("MARSHAL_ENTITY_ID", langext.Ptr(400))
	TypeInvalidCSID     = NewType("INVALID_CSID", langext.Ptr(400))

	TypeGoogleStatuscode = NewType("GOOGLE_STATUSCODE", langext.Ptr(400))
	TypeGoogleResponse   = NewType("GOOGLE_RESPONSE", langext.Ptr(400))

	TypeUnauthorized = NewType("UNAUTHORIZED", langext.Ptr(401))
	TypeAuthFailed   = NewType("AUTH_FAILED", langext.Ptr(401))
)

Functions

func HasSourceMessage added in v0.0.188

func HasSourceMessage(e error, msg string) bool

HasSourceMessage tests if the supplied error stems originally from an error with the message msg

func Init

func Init(cfg ErrorPackageConfigInit)

Init initializes the exerr packages Must be called at the program start, before (!) any errors Is not thread-safe

func Initialized added in v0.0.325

func Initialized() bool

func IsFrom added in v0.0.188

func IsFrom(e error, original error) bool

IsFrom test if the supplied error stems originally from original

func IsType added in v0.0.188

func IsType(err error, errType ErrorType) bool

IsType test if the supplied error is of the specified ErrorType.

func MessageMatch added in v0.0.188

func MessageMatch(e error, matcher func(string) bool) bool

func RegisterListener

func RegisterListener(l Listener)

Types

type AnyWrap

type AnyWrap struct {
	Type    string
	Json    string
	IsError bool
	IsNil   bool
}

func (AnyWrap) Serialize

func (w AnyWrap) Serialize() string

func (AnyWrap) String

func (w AnyWrap) String() string

type Builder

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

func Get

func Get(err error) *Builder

func New

func New(t ErrorType, msg string) *Builder

func Wrap

func Wrap(err error, msg string) *Builder

func (*Builder) Any

func (b *Builder) Any(key string, val any) *Builder

func (*Builder) Bool

func (b *Builder) Bool(key string, val bool) *Builder

func (*Builder) Build

func (b *Builder) Build() error

Build creates a new error, ready to pass up the stack If the errors is not SevWarn or SevInfo it gets also logged (in short form, without stacktrace) onto stdout Can be gloablly configured with ZeroLogErrTraces and ZeroLogAllTraces Can be locally suppressed with Builder.NoLog()

func (*Builder) Bytes

func (b *Builder) Bytes(key string, val []byte) *Builder

func (*Builder) Dur

func (b *Builder) Dur(key string, val time.Duration) *Builder

func (*Builder) Enum added in v0.0.235

func (b *Builder) Enum(key string, val enums.Enum) *Builder

func (*Builder) Err

func (b *Builder) Err() *Builder

Err changes the Severity to ERROR (default) The error will be:

  • On Build():

  • Short-Logged as Err

  • On Print():

  • Logged as Err

  • Send to the error-service

  • On Output():

  • Logged as Err

  • Send to the error-service

func (*Builder) Errs

func (b *Builder) Errs(key string, val []error) *Builder

func (*Builder) Fatal

func (b *Builder) Fatal()

Fatal prints the error and terminates the program If the error is SevErr we also send it to the error-service

func (*Builder) Float32

func (b *Builder) Float32(key string, val float32) *Builder

func (*Builder) Float64

func (b *Builder) Float64(key string, val float64) *Builder

func (*Builder) Format

func (b *Builder) Format(level LogPrintLevel) string

func (*Builder) GinReq

func (b *Builder) GinReq(ctx context.Context, g *gin.Context, req *http.Request) *Builder

func (*Builder) Id

func (b *Builder) Id(key string, val fmt.Stringer) *Builder

func (*Builder) Info

func (b *Builder) Info() *Builder

Info changes the Severity to INFO The error will be:

  • On Build():

  • -(nothing)-

  • On Print():

  • -(nothing)-

  • On Output():

  • -(nothing)-

func (*Builder) Int

func (b *Builder) Int(key string, val int) *Builder

func (*Builder) Int16

func (b *Builder) Int16(key string, val int16) *Builder

func (*Builder) Int32

func (b *Builder) Int32(key string, val int32) *Builder

func (*Builder) Int64

func (b *Builder) Int64(key string, val int64) *Builder

func (*Builder) Int8

func (b *Builder) Int8(key string, val int8) *Builder

func (*Builder) Interface

func (b *Builder) Interface(key string, val interface{}) *Builder

func (*Builder) Ints

func (b *Builder) Ints(key string, val []int) *Builder

func (*Builder) Ints32

func (b *Builder) Ints32(key string, val []int32) *Builder

func (*Builder) NoLog added in v0.0.321

func (b *Builder) NoLog() *Builder

func (*Builder) ObjectID

func (b *Builder) ObjectID(key string, val primitive.ObjectID) *Builder

func (*Builder) Output

func (b *Builder) Output(ctx context.Context, g *gin.Context)

Output prints the error onto the gin stdout. The error also gets printed to stdout/stderr If the error is SevErr|SevFatal we also send it to the error-service

func (*Builder) Print

func (b *Builder) Print()

Print prints the error If the error is SevErr we also send it to the error-service

func (*Builder) Stack

func (b *Builder) Stack() *Builder

func (*Builder) Str

func (b *Builder) Str(key string, val string) *Builder

func (*Builder) StrPtr

func (b *Builder) StrPtr(key string, val *string) *Builder

func (*Builder) Stringer added in v0.0.223

func (b *Builder) Stringer(key string, val fmt.Stringer) *Builder

func (*Builder) Strs

func (b *Builder) Strs(key string, val []string) *Builder

func (*Builder) System

func (b *Builder) System() *Builder

func (*Builder) Time

func (b *Builder) Time(key string, val time.Time) *Builder

func (*Builder) Type

func (b *Builder) Type(key string, cls interface{}) *Builder

func (*Builder) User

func (b *Builder) User() *Builder

User sets the Category to CatUser

Errors with category

func (*Builder) Warn

func (b *Builder) Warn() *Builder

Warn changes the Severity to WARN The error will be:

  • On Build():

  • -(nothing)-

  • On Print():

  • Short-Logged as Warn

  • On Output():

  • Logged as Warn

func (*Builder) WithMessage

func (b *Builder) WithMessage(msg string) *Builder

func (*Builder) WithStatuscode

func (b *Builder) WithStatuscode(status int) *Builder

func (*Builder) WithType

func (b *Builder) WithType(t ErrorType) *Builder

type EnumWrap added in v0.0.235

type EnumWrap struct {
	Type        string
	ValueString string
	ValueRaw    enums.Enum // `ValueRaw` is lost during serialization roundtrip
	IsNil       bool
}

func (EnumWrap) Serialize added in v0.0.235

func (w EnumWrap) Serialize() string

func (EnumWrap) String added in v0.0.235

func (w EnumWrap) String() string

type ErrorCategory

type ErrorCategory struct{ Category string }

type ErrorPackageConfig

type ErrorPackageConfig struct {
	ZeroLogErrTraces       bool                                             // autom print zerolog logs on .Build()  (for SevErr and SevFatal)
	ZeroLogAllTraces       bool                                             // autom print zerolog logs on .Build()  (for all Severities)
	RecursiveErrors        bool                                             // errors contains their Origin-Error
	ExtendedGinOutput      bool                                             // Log extended data (trace, meta, ...) to gin in err.Output()
	IncludeMetaInGinOutput bool                                             // Log meta fields ( from e.g. `.Str(key, val).Build()` ) to gin in err.Output()
	ExtendGinOutput        func(err *ExErr, json map[string]any)            // (Optionally) extend the gin output with more fields
	ExtendGinDataOutput    func(err *ExErr, depth int, json map[string]any) // (Optionally) extend the gin `__data` output with more fields
	DisableErrorWrapping   bool                                             // Disables the exerr.Wrap()...Build() function - will always return the original error
	ZeroLogErrGinOutput    bool                                             // autom print zerolog logs on ginext.Error() / .Output(gin)  (for SevErr and SevFatal)
	ZeroLogAllGinOutput    bool                                             // autom print zerolog logs on ginext.Error() / .Output(gin)  (for all Severities)
}

type ErrorPackageConfigInit

type ErrorPackageConfigInit struct {
	ZeroLogErrTraces       *bool
	ZeroLogAllTraces       *bool
	RecursiveErrors        *bool
	ExtendedGinOutput      *bool
	IncludeMetaInGinOutput *bool
	ExtendGinOutput        func(err *ExErr, json map[string]any)
	ExtendGinDataOutput    func(err *ExErr, depth int, json map[string]any)
	DisableErrorWrapping   *bool
	ZeroLogErrGinOutput    *bool
	ZeroLogAllGinOutput    *bool
}

type ErrorSeverity

type ErrorSeverity struct{ Severity string }

type ErrorType

type ErrorType struct {
	Key               string
	DefaultStatusCode *int
}

func ListRegisteredTypes added in v0.0.362

func ListRegisteredTypes() []ErrorType

func NewType added in v0.0.190

func NewType(key string, defStatusCode *int) ErrorType

type ExErr

type ExErr struct {
	UniqueID string `json:"uniqueID"`

	Timestamp time.Time     `json:"timestamp"`
	Category  ErrorCategory `json:"category"`
	Severity  ErrorSeverity `json:"severity"`
	Type      ErrorType     `json:"type"`

	StatusCode *int `json:"statusCode"`

	Message        string `json:"message"`
	WrappedErrType string `json:"wrappedErrType"`
	WrappedErr     any    `json:"-"`
	Caller         string `json:"caller"`

	OriginalError *ExErr `json:"originalError"`

	Meta MetaMap `json:"meta"`
}

func FromError added in v0.0.189

func FromError(err error) *ExErr

func (*ExErr) As added in v0.0.224

func (ee *ExErr) As(target any) bool

As must be implemented so that error.As(x) works

func (*ExErr) CallListener added in v0.0.361

func (ee *ExErr) CallListener(m Method)

func (*ExErr) Depth added in v0.0.188

func (ee *ExErr) Depth() int

Depth returns the depth of recursively contained errors

func (*ExErr) Error

func (ee *ExErr) Error() string

func (*ExErr) FormatLog added in v0.0.188

func (ee *ExErr) FormatLog(lvl LogPrintLevel) string

func (*ExErr) GetMeta added in v0.0.356

func (ee *ExErr) GetMeta(key string) (any, bool)

GetMeta returns the meta value with the specified key this method recurses through all wrapped errors and returns the first matching meta value

func (*ExErr) GetMetaBool added in v0.0.357

func (ee *ExErr) GetMetaBool(key string) (bool, bool)

func (*ExErr) GetMetaFloat32 added in v0.0.357

func (ee *ExErr) GetMetaFloat32(key string) (float32, bool)

func (*ExErr) GetMetaFloat64 added in v0.0.357

func (ee *ExErr) GetMetaFloat64(key string) (float64, bool)

func (*ExErr) GetMetaInt added in v0.0.357

func (ee *ExErr) GetMetaInt(key string) (int, bool)

func (*ExErr) GetMetaString added in v0.0.357

func (ee *ExErr) GetMetaString(key string) (string, bool)

GetMetaString functions the same as GetMeta, but returns false if the type does not match

func (*ExErr) GetMetaTime added in v0.0.357

func (ee *ExErr) GetMetaTime(key string) (time.Time, bool)

func (*ExErr) Is

func (ee *ExErr) Is(e error) bool

Is must be implemented so that error.Is(x) works

func (*ExErr) Log added in v0.0.188

func (ee *ExErr) Log(evt *zerolog.Event)

func (*ExErr) Output added in v0.0.188

func (ee *ExErr) Output(g *gin.Context)

func (*ExErr) RecursiveCategory added in v0.0.188

func (ee *ExErr) RecursiveCategory() ErrorCategory

RecursiveCategory returns the ErrorCategory to use = first error (top-down) that has a statuscode set

func (*ExErr) RecursiveMessage added in v0.0.188

func (ee *ExErr) RecursiveMessage() string

RecursiveMessage returns the message to show = first error (top-down) that is not wrapping/foreign/empty = lowest level error (that is not empty) = fallback to self.message

func (*ExErr) RecursiveMeta added in v0.0.194

func (ee *ExErr) RecursiveMeta(key string) *MetaValue

RecursiveMeta searches (top-down) for teh first error that has a meta value with teh specified key and returns its value (or nil)

func (*ExErr) RecursiveStatuscode added in v0.0.188

func (ee *ExErr) RecursiveStatuscode() *int

RecursiveStatuscode returns the HTTP Statuscode to use = first error (top-down) that has a statuscode set

func (*ExErr) RecursiveType added in v0.0.188

func (ee *ExErr) RecursiveType() ErrorType

RecursiveType returns the statuscode to use = first error (top-down) that is not wrapping/empty

func (*ExErr) ShortLog added in v0.0.188

func (ee *ExErr) ShortLog(evt *zerolog.Event)

func (*ExErr) ToAPIJson added in v0.0.215

func (ee *ExErr) ToAPIJson(applyExtendListener bool, includeWrappedErrors bool, includeMetaFields bool) langext.H

ToAPIJson converts the ExError to a json object (the same object as used in the Output(gin) method)

Parameters:

  • [applyExtendListener]: if false the pkgconfig.ExtendGinOutput / pkgconfig.ExtendGinDataOutput will not be applied
  • [includeWrappedErrors]: if false we do not include the recursive/wrapped errors in `__data`
  • [includeMetaFields]: if true we also include meta-values (aka from `.Str(key, value).Build()`), needs includeWrappedErrors=true

func (*ExErr) ToDefaultAPIJson added in v0.0.349

func (ee *ExErr) ToDefaultAPIJson() (string, error)

func (*ExErr) Unwrap

func (ee *ExErr) Unwrap() error

Unwrap must be implemented so that some error.XXX methods work

type IDWrap

type IDWrap struct {
	Type  string
	Value string
	IsNil bool
}

func (IDWrap) Serialize

func (w IDWrap) Serialize() string

func (IDWrap) String

func (w IDWrap) String() string

type Listener

type Listener = func(method Method, v *ExErr)

type LogPrintLevel added in v0.0.188

type LogPrintLevel string
const (
	LogPrintFull     LogPrintLevel = "Full"
	LogPrintOverview LogPrintLevel = "Overview"
	LogPrintShort    LogPrintLevel = "Short"
)

type MetaMap

type MetaMap map[string]MetaValue

func (MetaMap) Any

func (mm MetaMap) Any() bool

func (MetaMap) Apply

func (mm MetaMap) Apply(evt *zerolog.Event, limitLen *int) *zerolog.Event

func (MetaMap) FormatMultiLine

func (mm MetaMap) FormatMultiLine(indentFront string, indentKeys string, maxLenValue int) string

func (MetaMap) FormatOneLine

func (mm MetaMap) FormatOneLine(singleMaxLen int) string

type MetaValue

type MetaValue struct {
	DataType metaDataType `json:"dataType"`
	Value    interface{}  `json:"value"`
}

func (MetaValue) Apply

func (v MetaValue) Apply(key string, evt *zerolog.Event, limitLen *int) *zerolog.Event

func (*MetaValue) Deserialize

func (v *MetaValue) Deserialize(value string, datatype metaDataType) error

func (MetaValue) MarshalBSON

func (v MetaValue) MarshalBSON() ([]byte, error)

func (MetaValue) MarshalJSON

func (v MetaValue) MarshalJSON() ([]byte, error)

func (MetaValue) SerializeValue

func (v MetaValue) SerializeValue() (string, error)

func (MetaValue) ShortString

func (v MetaValue) ShortString(lim int) string

func (*MetaValue) UnmarshalBSON

func (v *MetaValue) UnmarshalBSON(bytes []byte) error

func (*MetaValue) UnmarshalJSON

func (v *MetaValue) UnmarshalJSON(data []byte) error

func (MetaValue) ValueString

func (v MetaValue) ValueString() string

type Method

type Method string
const (
	MethodOutput Method = "OUTPUT"
	MethodPrint  Method = "PRINT"
	MethodBuild  Method = "BUILD"
	MethodFatal  Method = "FATAL"
)

Jump to

Keyboard shortcuts

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