errors

package module
v0.0.0-...-ad407e6 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2017 License: BSD-3-Clause Imports: 4 Imported by: 4

README

phayes/errors: Better error handling for go

GoDoc Build Status Go Report Card Coverage Status

Go's standard errors package is a simple error package for handling errors, and works fine for shallow codebases, but has several shortcomings that phayes/errors hopes to remediate.

The biggest anti-pattern that the standard errors package encourages is one we are all familiar with:

    if err != nil
        return errors.New(err.Error() + ". Some more details about the error")
    }

This anti-pattern is corrected in phayes/errors by allowing you to cleanly wrap one error with another like so:

    if err != nil {
        return errors.Append(err, "Some more details about the error")
    }

This allows us to cleanly add more details to an error, while preseving the underlying error for later inspection.

It also plays nicely with standard library errors and predefined errors

    import (
        "github.com/phayes/errors"
        "io"
    )

    var ErrFailedStream = errors.New("Failed to read stream.")

    func ReadStream(b []byte) error {
        n, err := reader.Read(b)
        if err != nil {
            return errors.Append(ErrFailedStream, err)
        }
    }

    func main() {
        var b []byte
        err := ReadStream(b)
        if err != nil {
            if errors.IsA(err, io.EOF) {
                return // Success!
            } else {
                log.Fatal(err) // Prints "Failed to read stream. unexpected EOF"
            }
        }
    }

Wrapping errors

At it's most basic, phayes/errors is a drop in replacement for the standard error package.

    err := errors.New("Could not parse input")

However, it also provides the ability to wrap an error to give it more context

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

    func ReadStream(b []byte) error {
        n, err := reader.Read(b)
        if err != nil {
	        return errors.Wraps(err, "Failed to read stream.")
        }
    }

    func main() {
    	var b []byte
    	err := ReadStream(b)
    	if err != nil {
    		log.Fatal(err) // Prints "Failed to read stream. unexpected EOF"
    	}
    }

Inspecting errors

Use the IsA function to check to if the error, or any of it's inner errors, is what you're after. This is fully compatible with errors that are not part of phayes/errors. For example:

    func main() {
        var b []byte
        err := ReadStream(b)
        if err != nil {
            if errors.IsA(err, io.EOF) {
                return // Success!
            } else {
                log.Fatal(err)
            }
        }
    }

Documentation

Overview

Package errors provides better error handling.

Go's standard `errors` package is a simple error package for handling errors, and works fine for shallow codebases, but has several shortcomings that `phayes/errors` hopes to remediate.

The biggest anti-pattern that the standard errors package encourages is one we are all familiar with:

if err != nil
    return errors.New(err.Error() + ". Some more details about the error")
}

This anti-pattern is corrected in phayes/errors by allowing you to cleanly wrap one error with another like so:

if err != nil {
    return errors.Append(err, "Some more details about the error")
}

This allows us to cleanly add more details to an error, while preseving the underlying error for later inspection.

It also plays nicely with standard library errors and predefined errors:

import (
    "github.com/phayes/errors"
    "io"
)

var ErrFailedStream = errors.New("Failed to read stream.")

func ReadStream(b []byte) error {
    n, err := reader.Read(b)
    if err != nil {
        return errors.Append(ErrFailedStream, err)
    }
}

func main() {
    var b []byte
    err := ReadStream(b)
    if err != nil {
        if errors.IsA(err, io.EOF) {
            return // Success!
        } else {
            log.Fatal(err) // Prints "Failed to read stream. unexpected EOF"
        }
    }
}

Wrapping errors

At it's most basic, `phayes/errors` is a drop in replacement for the standard error package.

err := errors.New("Could not parse input")

However, it also provides the ability to wrap an error to give it more context:

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

    func ReadStream(b []byte) error {
        n, err := reader.Read(b)
        if err != nil {
	        return errors.Wraps(err, "Failed to read stream.")
        }
    }

    func main() {
    	var b []byte
    	err := ReadStream(b)
    	if err != nil {
    		log.Fatal(err) // Prints "Failed to read stream. unexpected EOF"
    	}
    }

Inspecting errors

Use the `IsA` function to check to if the error, or any of it's inner errors, is what you're after. This is fully compatible with errors that are not part of phayes/errors. For example:

func main() {
    var b []byte
    err := ReadStream(b)
    if err != nil {
        if errors.IsA(err, io.EOF) {
            return // Success!
        } else {
            log.Fatal(err)
        }
    }
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Append

func Append(outerErr error, innerErr error) error

Append more information to the error. The reverse of Wrap.

func Appendf

func Appendf(outerErr error, format string, args ...interface{}) error

Appendf appends more information to the error using formatting. The reverse of Wrapf.

func Appends

func Appends(outerErr error, inner string) error

Appends more information to the error using a string. The reverse of Wraps.

func Cause

func Cause(err error) error

Cause returns the root cause of the given error. If err does not implement phayes.Error, it returns err itself.

func Equal

func Equal(e1 error, e2 error) bool

Equal checks to see if two errors are the same

func IsA

func IsA(outerErr error, innerErr error) bool

IsA checks if two errors are the same or if the first contains the second This will recursively check their inner components to see if one is an instance of the other

func New

func New(s string) error

New create new error from string. It intentionally mirrors the standard "errors" module so as to be a drop-in replacement

func Newf

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

Newf is the same as New, but with fmt.Printf-style parameters. This is a replacement for fmt.Errorf.

func Wrap

func Wrap(innerErr error, outerErr error) error

Wrap the first error in the second error. Reverse of Append

func Wrapf

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

Wrapf is the same as Wraps, but with fmt.Printf-style parameters. Reverse of Appendf

func Wraps

func Wraps(err error, outer string) error

Wraps wraps an error in a new error using the provided string. Reverse of Appends

Types

type DefaultError

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

DefaultError is the default implementation of Error interface

func (DefaultError) Base

func (e DefaultError) Base() error

Base gets the base error that forms the basis of the DefaultError - returns a copy of itself without inners

func (DefaultError) Error

func (e DefaultError) Error() string

Error returns a string with all available error information, including inner errors that are wrapped by this errors.

func (DefaultError) Inner

func (e DefaultError) Inner() error

Inner gets the inner error that is wrapped by this error

func (DefaultError) Message

func (e DefaultError) Message() string

Message returns a string with error information, excluding inner errors

func (DefaultError) Wrap

func (e DefaultError) Wrap(err error) Error

Wrap the passed error in this error and return a copy

type Error

type Error interface {
	// This returns the error message without inner errors
	Message() string

	// Get the inner error. Will return nil if there is no inner error
	Inner() error

	// Wrap the given error. Calling Inner() should retreive it. Return a copy of the outer error as an Error.
	Wrap(error) Error

	// Base() should return a copy of the Error without any inners
	// This method is called to check two errors for equality
	Base() error

	// Implements the built-in error interface.
	Error() string
}

Error interface may be implemented by other packages

type ErrorSet

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

ErrorSet is a set of errors that can be collected together in a non-heirarchical manner.

func NewErrorSet

func NewErrorSet() *ErrorSet

NewErrorSet creates a new empty ErrorSet

func (*ErrorSet) Add

func (e *ErrorSet) Add(key string, err error)

Add an error to the error set

func (*ErrorSet) Error

func (e *ErrorSet) Error() string

Return Error as string

func (*ErrorSet) Get

func (e *ErrorSet) Get(key string) error

Get an error from the error set

func (*ErrorSet) GetAll

func (e *ErrorSet) GetAll() map[string]error

GetAll Gets all errors from the error set

func (*ErrorSet) HasErrors

func (e *ErrorSet) HasErrors() bool

HasErrors returns true if the ErrorSet contains an error

Jump to

Keyboard shortcuts

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