errors

package
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: Aug 7, 2020 License: Apache-2.0, Apache-2.0 Imports: 7 Imported by: 21

README

Neuron Logo

Errors Go Report Card GoDoc Build Status Coverage Status License

Package errors provides simple golang error and classification primitives.

Class

The package defines blazingly fast classification system. A Class is an uint32 wrapper, composed of the Major, Minor and Index subclassifications. Each subclassifaction has different bitwise length. A major is composed of 8, minor 10 and index of 14 bits - total 32bits.

Example:

 00000010101000101000010011001111 which decomposes into:
 00000010 - major (8 bit)
         1010001010 - minor (10 bit)
                   00010011001111 - index (14 bit)

The class concept was inspired by the need of multiple errors with the same logic but different messages.

A class might be composed in three different ways:

  • Major only - the class is Major singleton.
  • Major, Minor only - classes that don't need triple subclassification divison.
  • Major, Minor, Index - classes that decomposes

Use NewMajor or MustNewMajor functions to create Major, NewMinor or MustNewMinor for new Minor and NewIndex or MustNewIndex for new Index.

Interfaces

The package provides simple error handling interfaces and functions. It allows to create simple and detailed classified errors.

ClassError

A ClassError is the interface that provides error classification with theClass method.

DetailedError

DetailedError is the interface used for errors that stores and handles human readable details, contains it's instance id and runtime call operation. Implements ClassError, Detailer, Operationer, Indexer, error interfaces.

Detailer

Detailer interface allows to set and get the human readable details - full sentences.

Operationer

OperationError is the interface used to get the runtime operation information.

Indexer

Indexer is the interface used to obtain 'ID' for each error instance.

Error handling

This package contains two error structure implementations:

Simple Error

A simple error implements ClassError interface. It is lightweight error that contains only a message and it's class.

Created by the New and Newf functions.

Example:

import "github.com/neuronlabs/neuron/errors"
// let's assume we have some ClassInvalidRequest already defined.
var ClassInvalidInput errors.Class

func createValue(input int) error {
    if input < 0 {
        return errors.New(ClassInvalidInput, "provided input lower than zero")
    }

    if input > 50 {
        return errors.Newf(ClassInvalidInput, "provided input value: '%d' is not valid", input) 
    }
    // do the logic here
    return nil
}
Detailed Error

The detailed error struct (detailedError) implements DetailedError.

It contains a lot of information about given error instance:

  • Human readable Details
  • Runtime function call Operations
  • Unique error instance ID

In order to create detailed error use the NewDet or NewDetf functions.

Example
import (
    "fmt"
    "os"

    "github.com/neuronlabs/neuron/errors"
)

var (
    ClInputInvalidValue errors.Class
    ClInputNotProvided  errors.Class
)

func init() {
    initClasses()
}

func initClasses() {
    inputMjr := errors.MustNewMajor()
    invalidValueMnr := errors.MustNewMinor(inputMjr)
    ClInputInvalidValue = errors.MustNewMinorClass(inputMjr, invalidValueMnr)
    
    inputNotProvidedMnr := errors.MustNewMinor(inputMjr)
    ClInputNotProvided = errors.MustNewMinorClass(inputMjr, inputNotProvidedMnr)
}


func main() {
    input, err := getInput()
    if err == nil {
        // Everything is fine.
        os.Exit(0)
    }

    if classed, ok := err.(errors.ClassError); ok {
        if classed.Class() == ClInputNotProvided {
            fmt.Println("No required integer arguments provided.")
            os.Exit(1)
        }
    }

    var details string
    detailed, ok := err.(errors.DetailedError)
    if ok {
        details = detailed.Details()
    } else {
        details = err.Error()
    }
    fmt.Printf("Invalid input value provided: '%s'\n", details)
    os.Exit(1)    
}


func checkInput(input int) error {
    if input < 0 {
        err := errors.NewDet(ClassInputInvalidValue, "provided input lower than zero")        
        err.SetDetailsf("The input value provided to the function is invalid. The value must be greater than zero.")
        return err
    }

    if input > 50 {
        err := errors.NewDetf(ClassInvalidInput, "provided input value: '%d' is not valid", input) 
        err.SetDetailsf("The input value: '%d' provided to the function is invalid. The value can't be greater than '50'.", input)
        return err
    }
    // do the logic here
    return nil
}



func getInput() (int, error) {
    if len(os.Args) == 0 {
        return errors.New(ClInputNotProvided, "no input provided")
    }

    input, err := strconv.Atoi(os.Args[0])
    if err != nil {
        err := errors.NewDetf(ClInputInvalidValue, "provided input is not an integer")        
        err.SetDetail(err.Error())
        return 0, err
    }

    if err = checkInput(input); err != nil {
        return 0, err
    }
    return input, nil
}

Documentation

Overview

Package errors provides lightweight error handling and classification primitives.

The package defines blazing fast classification system. A class is composed of the major, minor and index sub classifications. Each sub classification has different bitwise length with total of 32 bits. Thus a Class is a wrapper over uint32. A major is composed of 8, minor 10 and index of 14 bits.

Example: Class with decimal value of 44205263, in a binary form equals to

 00000010101000101000010011001111 which decomposes into:
	00000010 - major (8 bit)
		    1010001010 - minor (10 bit)
					  00010011001111 - index (14 bit)

The class concept was inspired by the need of multiple errors with the same logic but different messages.

The package provides simple error handling interfaces and functions. It allows to create simple and detailed classified errors.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ClInvalidMajor defines the invalid major error classification.
	ClInvalidMajor Class
	// ClInvalidMinor defines the invalid minor error classification.
	ClInvalidMinor Class
	// ClInvalidIndex defines the invalid index error classification.
	ClInvalidIndex Class
	// MjrInternal is the major internal error class.
	MjrInternal Major
	// ClassInternal is the general internal error.
	ClassInternal Class
)

Functions

func IsClass added in v0.16.0

func IsClass(err error, class Class) bool

IsClass checks if given error is of given 'class'.

Types

type Class added in v0.16.0

type Class uint32

Class is the error classification model. It is composed of the major, minor and index sub classifications. Each sub classification is a different length number, where major is composed of 8, minor 10 and index of 14 bits. Example:

 44205263 in a binary form is:

 00000010101000101000010011001111 which decomposes into:
	00000010 - major (8 bit) - 2
		    1010001010 - minor (10 bit) - 650
					  00010011001111 - index (14 bit) - 1231

Major should be a global scope division like 'Repository', 'Marshaler', 'Controller' etc. Minor should divide the 'major' into subclasses like the Repository filter builders, marshaler - invalid field etc. Index is the most precise classification - i.e. Repository - filter builder - unsupported operator.

func MustNewClass added in v0.16.0

func MustNewClass(mjr Major, mnr Minor, index Index) Class

MustNewClass gets new class from the provided 'minor' and 'index'. Panics if any of the arguments is not valid or out of bands.

func MustNewClassWIndex added in v0.16.0

func MustNewClassWIndex(mjr Major, mnr Minor) Class

MustNewClassWIndex creates new 'mjr' Major, 'mnr' Minor 'index' and then a new Class for provided triplet. Panics on error.

func MustNewMajorClass added in v0.16.0

func MustNewMajorClass(mjr Major) Class

MustNewMajorClass creates Class from the provided 'mjr' Major. This class contains zero valued 'Minor' and 'Index'. Panics if provided 'mjr' is invalid.

func MustNewMinorClass added in v0.16.0

func MustNewMinorClass(mjr Major, mnr Minor) Class

MustNewMinorClass creates a class from the provided 'mjr' Major and 'mnr' Minor. Panics when any of the provided arguments is invalid.

func NewClass added in v0.16.0

func NewClass(mjr Major, mnr Minor, index Index) (Class, error)

NewClass gets new class from the provided 'minor' and 'index'. If any of the arguments is not valid or out of bands the function returns an error.

func NewClassWIndex added in v0.16.0

func NewClassWIndex(mjr Major, mnr Minor) (Class, error)

NewClassWIndex creates new index and class for provided 'mjr' Major and 'mnr' Minor. Returns error if any of the input values are not valid.

func NewMajorClass added in v0.16.0

func NewMajorClass(mjr Major) (Class, error)

NewMajorClass creates Class from the provided 'mjr' Major. This class contains zero valued 'Minor' and 'Index'. Returns error if the 'mjr' is invalid.

func NewMinorClass added in v0.16.0

func NewMinorClass(mjr Major, mnr Minor) (Class, error)

NewMinorClass gets the class from provided 'minor'. The function gets minor's major and gets the major/minor class.

func (Class) Index added in v0.16.0

func (c Class) Index() Index

Index is a four digit number unique within given minor and major.

func (Class) Major added in v0.16.0

func (c Class) Major() Major

Major is a single digit major classification.

func (Class) Minor added in v0.16.0

func (c Class) Minor() Minor

Minor is a double digit minor classification unique within given major.

type ClassError added in v0.16.0

type ClassError interface {
	error
	// Class gets current error classification.
	Class() Class
}

ClassError is the interface used for all errors that uses classification system.

func New added in v0.16.0

func New(c Class, msg string) ClassError

New creates simple ClassError for provided 'c' Class and 'msg' message.

func Newf added in v0.16.0

func Newf(c Class, format string, args ...interface{}) ClassError

Newf creates simple formatted ClassError for provided 'c' Class, 'format' and arguments 'args'.

type DetailedError added in v0.16.0

type DetailedError struct {
	// ID is a unique error instance identification number.
	ID uuid.UUID
	// Classification defines the error classification.
	Classification Class
	// details contains the detailed information.
	Details string
	// message is a message used as a string for the
	// golang error interface implementation.
	Message string
	// Operation is the operation name when the error occurred.
	Operation string
}

DetailedError is the class based error definition. Each instance has it's own traceable ID. It contains also a Class variable that might be comparable in logic.

func NewDet added in v0.16.0

func NewDet(c Class, message string) *DetailedError

NewDet creates DetailedError with given 'class' and message 'message'.

func NewDetf added in v0.16.0

func NewDetf(c Class, format string, args ...interface{}) *DetailedError

NewDetf creates DetailedError instance with provided 'class' with formatted message. DetailedError implements ClassError interface.

func (*DetailedError) Class added in v0.16.0

func (e *DetailedError) Class() Class

Class implements ClassError.

func (*DetailedError) Error added in v0.16.0

func (e *DetailedError) Error() string

DetailedError implements error interface.

func (*DetailedError) WithDetail added in v0.16.0

func (e *DetailedError) WithDetail(detail string) *DetailedError

WithDetail sets error detail.

func (*DetailedError) WithDetailf added in v0.16.0

func (e *DetailedError) WithDetailf(format string, values ...interface{}) *DetailedError

WithDetailf sets error detail.

type Index added in v0.16.0

type Index uint16

Index is a 14 bit length lowest level error classification. It defines the most accurate class division. It's maximum size gives 2^14 - 16384 - index combinations for each minor.

func MustNewIndex added in v0.16.0

func MustNewIndex(mjr Major, mnr Minor) Index

MustNewIndex creates new Index for the 'mjr' Major and 'mnr' Minor. Panics if 'mjr' or 'mnr' are not valid.

func NewIndex added in v0.16.0

func NewIndex(mjr Major, mnr Minor) (Index, error)

NewIndex creates new Index for the 'mjr' Major and 'mnr' Minor. Returns error if the 'mjr' or 'mnr' are not valid.

func (Index) Valid added in v0.16.0

func (i Index) Valid() bool

Valid checks if the provided index is valid.

type Major added in v0.16.0

type Major uint8

Major is the highest level sub classification. It is of maximum 8 bit size, which gives 2^8 - 256 combinations.

func MustNewMajor added in v0.16.0

func MustNewMajor() Major

MustNewMajor creates new major error classification. Panics if reached maximum number of possible majors.

func NewMajor added in v0.16.0

func NewMajor() (Major, error)

NewMajor creates new Major classification.

func (Major) Valid added in v0.16.0

func (m Major) Valid() bool

Valid checks if the major value isn't greater than the allowed size and if it's value is non-zero.

type Minor added in v0.16.0

type Minor uint16

Minor is mid level error sub classification. It is a 10 bit long value, which give 2^10 - 1024 - combinations for each major.

func MustNewMinor added in v0.16.0

func MustNewMinor(mjr Major) Minor

MustNewMinor creates new Minor error classification for provided 'mjr' Major. Panics if the 'mjr' is not valid.

func NewMinor added in v0.16.0

func NewMinor(mjr Major) (Minor, error)

NewMinor creates new Minor error classification for provided 'mjr' Major. Returns error if the 'mjr' is not valid.

func (Minor) Valid added in v0.16.0

func (m Minor) Valid() bool

Valid checks if the Minor is valid.

type MultiError added in v0.16.0

type MultiError []ClassError

MultiError is the slice of errors parsable into a single error.

func (MultiError) Error added in v0.16.0

func (m MultiError) Error() string

Error implements error interface.

func (MultiError) HasMajor added in v0.16.0

func (m MultiError) HasMajor(mjr Major) bool

HasMajor checks if provided 'mjr' occurs in given multi error slice.

Jump to

Keyboard shortcuts

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