errdata

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2022 License: MIT Imports: 2 Imported by: 2

README

errdata

GoDoc Sourcegraph Go Report Card

errdata helps with associating some data to error classes.

Adding data

The Set function associates some data with some error class and key. For example:

var (
	Unauthorized = errs.Class("unauthorized")
	NotFound     = errs.Class("not found")
)

type httpErrorCodeKey struct{}

func init() {
	errdata.Set(Unauthorized, httpErrorCodeKey{}, http.StatusUnauthorized)
	errdata.Set(NotFound, httpErrorCodeKey{}, http.StatusNotFound)
}

Why do that? Get can read the associated data for an error if it was wrapped by any of the Classes you have set data on. For example:

func getStatusCode(err error) int {
	code, _ := errdata.Get(err, httpErrorCodeKey{}).(int)
	if code == 0 {
		code = http.StatusInternalServerError
	}
	return code
}

If the error has been wrapped by multiple classes for that key, the value for the most recently wrapped class is returned. For example:

func whatStatusCodeCode() {
	err := NotFound.Wrap(Unauthorized.New("test"))
	fmt.Println(getStatusCode(err))

	// output:
	// 404
}
Contributing

errdata is released under an MIT License. If you want to contribute, be sure to add yourself to the list in AUTHORS.

Documentation

Overview

Package errdata helps with associating some data to error classes

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Get

func Get(err error, key interface{}) interface{}

Get returns the value associated to the key for the error if any of the classes the error is part of have a value associated for that key.

func Set

func Set(class *errs.Class, key interface{}, value interface{})

Set associates the value for the given key and class. Errors wrapped by the class will return the value in the call to Get for the key.

Types

This section is empty.

Jump to

Keyboard shortcuts

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