emperror

package module
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: Dec 28, 2018 License: MIT Imports: 5 Imported by: 0

README

Emperror

Build Status Go Report Card GolangCI GoDoc

The Emperor takes care of all errors personally.

Go's philosophy encourages to gracefully handle errors whenever possible, but some times recovering from an error is not possible.

In those cases handling the error means making the best effort to record every detail for later inspection, doing that as high in the application stack as possible.

This project provides tools (building on the well-known pkg/errors package) to make error handling easier.

Read more about the topic here:

Features

  • Various error handling strategies (eg. logging, third-party error services) using a simple interface
  • Error annotation with context (key-value pairs, HTTP request, etc)
  • Various helpers related to error handling (recovery from panics, etc)
  • Integrations with well-known error catchers and libraries:

Usage

Log errors

Logging is one of the most common target to record error events.

The reference implementation for logging with Emperror can be found in package logur. Logur is an opinionated logging toolkit supporting multiple logging libraries (like logrus).

Emperror comes with a set of handlers backed by logging frameworks too:

  • handler/logrushandler: logrus handler implementation

See GoDoc for detailed usage examples.

Attach context to an error

Following go-kit's logger context pattern Emperror gives you tools to attach context (eg. key-value pairs) to an error:

package main

import (
	"github.com/goph/emperror"
	"github.com/pkg/errors"
)

func foo() error { return errors.New("error") }

func bar() error {
	err := foo()
	if err != nil {
	    return emperror.With(err, "key", "value")
	}
	
	return nil
}

Note that (just like with go-kit's logger) the context is NOT a set of key-value pairs per se, but most tools will convert the slice to key-value pairs. This is to provide flexibility in error handling implementations.

Development

Install the dependencies:

$ make vendor # or dep ensure

When all coding and testing is done, please run the test suite:

$ make check

License

The MIT License (MIT). Please see License File for more information.

Documentation

Overview

Package emperror provides error handling solutions and tools for libraries and applications.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Context added in v0.8.0

func Context(err error) []interface{}

Context extracts the context key-value pairs from an error (or error chain).

func ExposeStackTrace added in v0.8.0

func ExposeStackTrace(err error) error

ExposeStackTrace exposes the stack trace (if any) in the outer error.

func ForEachCause added in v0.8.0

func ForEachCause(err error, fn func(err error) bool)

ForEachCause loops through an error chain and calls a function for each of them, starting with the topmost one.

The function can return false to break the loop before it ends.

func Handle added in v0.16.0

func Handle(handler Handler, err error)

Handle handles an error whenever it occurs.

func HandleRecover added in v0.1.1

func HandleRecover(handler Handler)

HandleRecover recovers from a panic and handles the error.

defer emperror.HandleRecover(errorHandler)

func Panic added in v0.15.0

func Panic(err error)

Panic panics if the passed error is not nil.

This function is useful with HandleRecover when panic is used as a flow control tool to stop the application.

func Recover added in v0.1.1

func Recover(r interface{}) (err error)

Recover accepts a recovered panic (if any) and converts it to an error (if necessary).

func StackTrace added in v0.8.0

func StackTrace(err error) (errors.StackTrace, bool)

StackTrace returns the stack trace from an error (if any).

func With added in v0.5.0

func With(err error, keyvals ...interface{}) error

With returns a new error with keyvals context appended to it. If the wrapped error is already a contextual error created by With keyvals is appended to the existing context, but a new error is returned.

func Wrap added in v0.11.0

func Wrap(err error, message string) error

Wrap returns an error annotating err with a stack trace at the point Wrap is called (if there is none attached to the error yet), and the supplied message. If err is nil, Wrap returns nil.

Note: do not use this method when passing errors between goroutines.

func WrapWith added in v0.12.0

func WrapWith(err error, message string, keyvals ...interface{}) error

WrapWith returns an error annotating err with a stack trace at the point Wrap is called (if there is none attached to the error yet), the supplied message, and the supplied context. If err is nil, Wrap returns nil.

Note: do not use this method when passing errors between goroutines.

func Wrapf added in v0.11.0

func Wrapf(err error, format string, args ...interface{}) error

Wrapf returns an error annotating err with a stack trace at the point Wrapf is call (if there is none attached to the error yet), and the format specifier. If err is nil, Wrapf returns nil.

Note: do not use this method when passing errors between goroutines.

Types

type Handler

type Handler interface {
	// Handle takes care of unhandled errors.
	Handle(err error)
}

Handler is responsible for handling an error.

This interface allows libraries to decouple from logging and error handling solutions.

func HandlerWith added in v0.7.0

func HandlerWith(handler Handler, keyvals ...interface{}) Handler

HandlerWith returns a new error handler with keyvals context appended to it. If the wrapped error handler is already a contextual error handler created by HandlerWith or HandlerWithPrefix keyvals is appended to the existing context, but a new error handler is returned.

The created handler will prepend it's own context to the handled errors.

func HandlerWithPrefix added in v0.7.0

func HandlerWithPrefix(handler Handler, keyvals ...interface{}) Handler

HandlerWithPrefix returns a new error handler with keyvals context prepended to it. If the wrapped error handler is already a contextual error handler created by HandlerWith or HandlerWithPrefix keyvals is prepended to the existing context, but a new error handler is returned.

The created handler will prepend it's own context to the handled errors.

func NewCompositeHandler

func NewCompositeHandler(handlers ...Handler) Handler

NewCompositeHandler returns a new compositeHandler.

func NewNoopHandler added in v0.16.0

func NewNoopHandler() Handler

NewNoopHandler creates a no-op error handler that discards all received errors. Useful in examples and as a fallback error handler.

type HandlerFunc added in v0.5.0

type HandlerFunc func(err error)

HandlerFunc wraps a function and turns it into an error handler.

func (HandlerFunc) Handle added in v0.5.0

func (h HandlerFunc) Handle(err error)

Handle calls the underlying log function.

type MultiErrorBuilder added in v0.5.0

type MultiErrorBuilder struct {
	Message        string
	SingleWrapMode SingleWrapMode
	// contains filtered or unexported fields
}

MultiErrorBuilder provides an interface for aggregating errors and exposing them as a single value.

func NewMultiErrorBuilder added in v0.5.0

func NewMultiErrorBuilder() *MultiErrorBuilder

NewMultiErrorBuilder returns a new MultiErrorBuilder.

func (*MultiErrorBuilder) Add added in v0.5.0

func (b *MultiErrorBuilder) Add(err error)

Add adds an error to the list.

Calling this method concurrently is not safe.

func (*MultiErrorBuilder) ErrOrNil added in v0.5.0

func (b *MultiErrorBuilder) ErrOrNil() error

ErrOrNil returns a MultiError the builder aggregates a list of errors, or returns nil if the list of errors is empty.

It is useful to avoid checking if there are any errors added to the list.

type SingleWrapMode added in v0.5.0

type SingleWrapMode int

SingleWrapMode defines how MultiErrorBuilder behaves when there is only one error in the list.

const (
	AlwaysWrap   SingleWrapMode = iota // Always return a MultiError.
	ReturnSingle                       // Return the single error.
)

These constants cause MultiErrorBuilder to behave as described if there is only one error in the list.

type TestHandler

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

TestHandler is a simple stub for the handler interface recording every error.

The TestHandler is safe for concurrent use.

func NewTestHandler

func NewTestHandler() *TestHandler

NewTestHandler returns a new TestHandler.

func (*TestHandler) Count added in v0.16.0

func (h *TestHandler) Count() int

Count returns the number of events recorded in the logger.

func (*TestHandler) Errors

func (h *TestHandler) Errors() []error

Errors returns all handled errors.

func (*TestHandler) Handle

func (h *TestHandler) Handle(err error)

Handle records the error.

func (*TestHandler) LastError added in v0.16.0

func (h *TestHandler) LastError() error

LastError returns the last handled error (if any).

Directories

Path Synopsis
handler
airbrakehandler
Package airbrakehandler provides Airbrake/Errbit integration.
Package airbrakehandler provides Airbrake/Errbit integration.
bugsnaghandler
Package bugsnaghandler provides Bugsnag integration.
Package bugsnaghandler provides Bugsnag integration.
logrushandler
Package logrushandler provides Logrus integration.
Package logrushandler provides Logrus integration.
rollbarhandler
Package rollbarhandler provides Rollbar integration.
Package rollbarhandler provides Rollbar integration.
internal

Jump to

Keyboard shortcuts

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