guru – zgo.at/guru Index | Examples | Files

package guru

import "zgo.at/guru"

Package guru provides Go errors with a Guru Meditation Code.

Example

Code:play 

package main

import (
	"fmt"
	"net/http"

	"github.com/pkg/errors"
	"github.com/teamwork/guru"
)

// Error constants.
const (
	CodeFruitOverflow = iota + 1
	CodeBoozeUnderrun
	CodeExpired
)

func main() {
	// Construct a new error.
	err := guru.New(CodeFruitOverflow, "too many bananas")
	fmt.Println(err) // error 1: too many bananas

	// Retrieve the error code
	code := guru.Code(err)
	fmt.Println(code) // 1

	// Add error code to existing error.
	err = errors.New("not enough beer")
	err = guru.WithCode(CodeBoozeUnderrun, err)
	fmt.Println(err) // error 2: not enough beer

	// Add error code to existing error with context.
	err = errors.New("Dennis Ritchie")
	err = guru.Wrap(CodeExpired, err, "no longer with us")
	fmt.Println(err) // error 3: Dennis Ritchie: no longer with us

	// For HTTP applications, it may be useful to directly the HTTP status codes:
	err = guru.New(http.StatusNotAcceptable, "Justin Bieber")
	fmt.Println(err) // error 406: Justin Bieber

	// Error codes can be overriden:
	err = guru.New(1, "oh noes")
	err = guru.WithCode(2, err)
	fmt.Println(guru.Code(err)) // 2
}

Index

Examples

Functions

func Code

func Code(err error) int

Code extracts the highest-level error code from the error or the errors it wraps. It will return 0 if the error does not implement the coder interface.

func Errorf

func Errorf(code int, format string, args ...interface{}) error

Errorf returns a new error message with stack trace and error code.

func HTTPUserError

func HTTPUserError(err error) bool

HTTPUserError reports if this HTTP status code is a user error (i.e. in the 4xx range).

func New

func New(code int, msg string) error

New returns a new error message with a stack trace and error code.

func WithCode

func WithCode(code int, err error) error

WithCode wraps an existing error with the provided error code and stack trace. It will return nil if err is nil.

func Wrap

func Wrap(code int, err error, msg string) error

Wrap returns an error annotating err with a stack trace, error code, and the supplied message. It will return nil if err is nil.

func Wrapf

func Wrapf(code int, err error, msg string, args ...interface{}) error

Wrapf returns an error annotating err with a stack trace, error code, and the format specifier. It will return nil if err is nil.

Source Files

guru.go http.go stack.go

Version
v1.0.0
Published
Apr 16, 2018
Platform
js/wasm
Imports
3 packages
Last checked
now

Tools for package owners.