Back to godoc.org
zgo.at/guru

package guru

v1.1.0
Latest Go to latest
Published: Apr 5, 2020 | License: MIT | Module: zgo.at/guru

Overview

Package guru provides Go errors with a Guru Meditation Code.

Example

Code:

package guru_test

import (
	"errors"
	"fmt"
	"net/http"

	"zgo.at/guru"
)

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

func Example() {
	// 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

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 an 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 an error code.

func WithCode

func WithCode(code int, err error) error

WithCode wraps an existing error with the provided error code. 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 an 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 an error code, and the format specifier. It will return nil if err is nil.

Documentation was rendered with GOOS=linux and GOARCH=amd64.

Jump to identifier

Keyboard shortcuts

? : This menu
f or F : Jump to identifier