errors

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2019 License: Apache-2.0 Imports: 7 Imported by: 16

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/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/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 leightweight error handling and classification primitives.

The package defines blazingly fast classification system. A class is composed of the major, minor and index subclassifications. Each subclassifaction 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

This section is empty.

Functions

This section is empty.

Types

type Class

type Class uint32

Class is the error classification model. It is composed of the major, minor and index subclassifications. Each subclassifaction 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.

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
)

func MustNewClass

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 v1.1.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

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

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

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 v1.1.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

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

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

func (c Class) Index() Index

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

func (Class) Major

func (c Class) Major() Major

Major is a single digit major classification.

func (Class) Minor

func (c Class) Minor() Minor

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

type ClassError

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

func New(c Class, msg string) ClassError

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

func Newf

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

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

type DetailedError

type DetailedError interface {
	ClassError
	Indexer
	Detailer
	Operationer
}

DetailedError is the error that implements ClassError, Detailer, Indexer, Operationer interfaces.

func NewDet

func NewDet(c Class, message string) DetailedError

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

func NewDetf

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

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

type Detailer

type Detailer interface {
	// Details are human readable information about the error.
	Details() string
	// SetDetails sets the detail for given error.
	SetDetails(message string)
	// SetDetailsf sets formatted detail function.
	SetDetailsf(format string, args ...interface{})
	// WrapDetails if Detailer contains any 'Details' then it would
	// be combined with the 'message'. Otherwise works as SetDetails.
	WrapDetails(message string)
	// WrapDetailsf if Detailer contains any 'Details' then it would
	// be combined with the formatted message. Otherwise works as SetDetailsf.
	WrapDetailsf(format string, args ...interface{})
}

Detailer is the interface that defines methods used for setting details (errors).

type Index

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

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

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

func (i Index) Valid() bool

Valid checks if the provided index is valid.

type Indexer

type Indexer interface {
	// ID gets a unique error instance identification number.
	ID() uuid.UUID
}

Indexer is the an enhanced error interface.

type Major

type Major uint8

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

func MustNewMajor added in v1.2.0

func MustNewMajor() Major

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

func NewMajor

func NewMajor() (Major, error)

NewMajor creates new Major classification.

func (Major) Valid

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

type Minor uint16

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

func MustNewMinor

func MustNewMinor(mjr Major) Minor

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

func NewMinor

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

func (m Minor) Valid() bool

Valid checks if the Minor is valid.

type MultiError

type MultiError []ClassError

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

func (MultiError) Error

func (m MultiError) Error() string

Error implements error interface.

func (MultiError) HasMajor

func (m MultiError) HasMajor(mjr Major) bool

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

type Operationer

type Operationer interface {
	// Operation gets the runtime information about the file:line and function
	// where the error was created.
	Operation() string
	// AppendOperation wraps the operation creating a chain of operations.
	AppendOperation(operation string)
}

Operationer is enhanced error interface. It contains and allows to get the run time operation name.

Jump to

Keyboard shortcuts

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