errors

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2021 License: MIT Imports: 4 Imported by: 12

README

errors GoDoc Build Status Coverage Status Go Report Card

Enterprise approach of error handling

Goals

  • Capture stack at once in the begining.
  • Enhance error with key/value pairs, later to be written into structurized log.
  • Enhance error with the code, what can be refered in documentation. (i.g. ORA-0600 in Oracle).
  • Enhance error with severity level.
  • Ability of drill down to the wrapped errors.
  • Chaining.

Usage

import (
    "github.com/axkit/errors"
)

func WriteJSON(w io.Writer, src interface{}) error {

    buf, err := json.Marshal(src)
    if err != nil {
        return errors.Catch(err).Critical().Set("obj", src).StatusCode(500)
    }
    return nil
}


func Div(a, b int) (int, error) {

    if b == 0 {
        return 0, errors.New("divizion by zero").Critica().SetPairs("a", a)
    }

    return a/b, nil
}

func (srv *CustomerService)CustomerByID(id int) (*Customer, error) {

    c, ok := srv.repo.CustomerByID(id)
    if !ok {
        return nil, errors.New("customer not found").Critical().Set("id", id).StatusCode(404)
    }

    return c, nil
}


Prague 2020

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultCallerFramesFunc holds default function used by function Catch()
	// to collect call frames.
	DefaultCallerFramesFunc func(offset int) []Frame = CallerFrames

	// CallingStackMaxLen holds maximum elements in the call frames.
	CallingStackMaxLen int = 15
)
View Source
var CaptureStackStopWord string

CaptureStackStopWord captures stack till the function name has not contains CaptureStackStopWord

The stack capturing ignored if it's empty or it's appeared in the first function name.

View Source
var ConsistencyFailed = func() *CatchedError {
	return newx("consistency failed").StatusCode(500).Severity(Critical)
}
View Source
var ErrorMethodMode = Single

ErrorMethodMode holds behavior of Error() method.

View Source
var Forbidden = func() *CatchedError {
	return newx("forbidden").StatusCode(403).Severity(Critical)
}
View Source
var InternalError = func() *CatchedError {
	return newx("internal error").StatusCode(500).Severity(Critical)
}
View Source
var InvalidRequestBody = func(s string) *CatchedError {
	return newx(s).StatusCode(400).Severity(Critical)
}
View Source
var LastNonPairedValue interface{} = "missed value"

LastNonPairedValue holds value to be assigned by SetPairs if amount of parameters is odd.

View Source
var NotFound = func(msg string) *CatchedError {
	return newx(msg).StatusCode(404).Severity(Medium)
}

NotFound объект не найден.

View Source
var Unauthorized = func() *CatchedError {
	return newx("unauthorized").StatusCode(401).Severity(Medium)
}
View Source
var UnprocessableEntity = func(s string) *CatchedError {
	return newx(s).StatusCode(422).Severity(Medium)
}
View Source
var ValidationFailed = func(msg string) *CatchedError {
	return newx(msg).StatusCode(400).Severity(Tiny)
}

Functions

func JSON

func JSON(err error) []byte

JSON returns JSON object if err is CatchedError or quoted string if not.

Types

type CatchedError

type CatchedError struct {
	Frames []Frame                `json:"frames,omitempty"`
	Fields map[string]interface{} `json:"-"`
	// contains filtered or unexported fields
}

CatchedError holds call stack

func Catch

func Catch(err error) *CatchedError

Catch wraps an error with capturing stack at the point of calling. A severity level is Tiny.

If err is already CapturedError, the stack does not capture again. It's assumed it was done before. The attributes Severity and StatusCode inherits but can be changed later.

if err == nil returns nil.

func CatchCustom

func CatchCustom(err error, stackcapture func() []Frame) *CatchedError

CatchCustom wraps an error with custom stack capturer.

func New

func New(msg string) *CatchedError

New returns CatchedError with stack at the point of calling with severity level Tiny. The function is used if there is no original error what can be wrapped.

func NewCritical

func NewCritical(msg string) *CatchedError

NewCritical returns CatchedError with stack at the point of calling and severity level Critical.

func NewMedium

func NewMedium(msg string) *CatchedError

NewMedium returns CatchedError with stack at the point of calling and severity level Medium.

func (*CatchedError) Code

func (ce *CatchedError) Code(code string) *CatchedError

Code sets business code of.

func (*CatchedError) Critical

func (ce *CatchedError) Critical() *CatchedError

Critical sets severity level to Critical.

func (CatchedError) Error

func (ce CatchedError) Error() string

Error implements interface golang/errors Error. Returns string, taking into account value of ErrorMethodMode.

If ErrorMethodMode == Multi, results build using LIFO principle.

func (*CatchedError) Get

func (ce *CatchedError) Get(key string) (interface{}, bool)

Get returns value by key.

func (*CatchedError) GetDefault

func (ce *CatchedError) GetDefault(key string, def interface{}) interface{}

GetDefault returns value by key. Returns def if not found.

func (*CatchedError) IsNotFound

func (ce *CatchedError) IsNotFound() bool

IsNotFound returns true if it's not found error wrapped.

func (*CatchedError) Last

func (ce *CatchedError) Last() *WrappedError

Last returns last wrapper.

func (*CatchedError) Len

func (ce *CatchedError) Len() int

Len returns amount of errors wrapped + 1.

func (*CatchedError) Medium

func (ce *CatchedError) Medium() *CatchedError

Medium sets severity level to Medium.

func (*CatchedError) Msg

func (ce *CatchedError) Msg(s string) *CatchedError

Msg replaces error message.

func (*CatchedError) Protect

func (ce *CatchedError) Protect() *CatchedError

Protect marks error as protected. An error with protection will not be visible to the user.

func (*CatchedError) Set

func (ce *CatchedError) Set(key string, val interface{}) *CatchedError

Set accociates a single key with value.

func (*CatchedError) SetPairs

func (ce *CatchedError) SetPairs(kvpairs ...interface{}) *CatchedError

SetPairs accociates multiple key/value pairs. SetPairs("id", 10, "name", "John") if amount of parameters is odd, SetPairs("id", 10, "name") uses LastNonPairedValue as the last value.

func (*CatchedError) SetStrs

func (ce *CatchedError) SetStrs(key string, strs ...string) *CatchedError

SetStrs accociates with the key multiple strings.

func (*CatchedError) SetVals

func (ce *CatchedError) SetVals(key string, vals ...interface{}) *CatchedError

SetVals accociates with the key multiple interfaces.

func (*CatchedError) Severity

func (ce *CatchedError) Severity(level SeverityLevel) *CatchedError

Severity set error's severity level. It's ignored if level is lower than current level.

func (*CatchedError) StatusCode

func (ce *CatchedError) StatusCode(code int) *CatchedError

StatusCode sets HTTP response code, recommended to be assigned.

func (*CatchedError) Strs

func (ce *CatchedError) Strs(exceptProtected bool) []string

Strs returns error messages of wrapped errors except last message and empty messages.

type Eventer

type Eventer interface {
	Str(key, val string) Eventer
	Strs(key string, vals []string) Eventer
	Fields(map[string]interface{}) Eventer
	Int(string, int) Eventer
}

type Frame

type Frame struct {
	Function string `json:"function"`
	File     string `json:"file"`
	Line     int    `json:"line"`
}

Frame describes content of a single stack frame stored with error.

func CallerFrames

func CallerFrames(offset int) []Frame

CallerFrames returns not more then slice of Frame.

type Mode

type Mode int

Mode describes allowed methods of response returned Error().

const (
	// Multi return all error messages separated by ": ".
	Multi Mode = 0

	// Single return message of last error in the stack.
	Single Mode = 1
)

type SeverityLevel

type SeverityLevel int

SeverityLevel describes error severity levels.

const (
	// Tiny classifies as expected, managed errors that do not require administrator attention.
	// It's not recommended to write a call stack to the journal file.
	//
	// Example: error related to validation of entered form fields.
	Tiny SeverityLevel = iota

	// Medium classifies an regular error. A call stack is written to the log.
	Medium

	// Critical classifies a significant error, requiring immediate attention.
	// An error occurrence fact shall be passed to the administrator in all possible ways.
	// A call stack is written to the log.
	Critical
)

func (SeverityLevel) MarshalJSON

func (sl SeverityLevel) MarshalJSON() ([]byte, error)

MarshalJSON implements json/Marsaller interface.

func (SeverityLevel) String

func (sl SeverityLevel) String() string

String returns severity level string representation.

type WrappedError

type WrappedError struct {

	// Message holds final error's Message.
	Message string `json:"message"`

	// Severity) holds severity level.
	Severity SeverityLevel `json:"severity"`

	// StatusCode holds HTTP status code, what is recommended to assign to HTTP response
	// if value is specified (above zero).
	StatusCode int `json:"-"`

	// Code holds application error code.
	Code string `json:"code,omitempty"`

	// Protected
	Protected bool `json:"-"`
	// contains filtered or unexported fields
}

WrappedError is a structure defining wrapped error.

func (WrappedError) Err

func (we WrappedError) Err() error

Err returns original error.

func (WrappedError) Error

func (we WrappedError) Error() string

Error implements standard Error interface.

Jump to

Keyboard shortcuts

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