File: README.md

package info (click to toggle)
golang-github-zeebo-errs 1.3.0-3
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 116 kB
  • sloc: makefile: 2
file content (60 lines) | stat: -rw-r--r-- 1,712 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# errdata

[![GoDoc](https://godoc.org/github.com/zeebo/errs/errdata?status.svg)](https://godoc.org/github.com/zeebo/errs/errdata)
[![Sourcegraph](https://sourcegraph.com/github.com/zeebo/errs/-/badge.svg)](https://sourcegraph.com/github.com/zeebo/errs?badge)
[![Go Report Card](https://goreportcard.com/badge/github.com/zeebo/errs/errdata)](https://goreportcard.com/report/github.com/zeebo/errs/errdata)

errdata helps with associating some data to error classes.

### Adding data

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

```go
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][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:

```go
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:

```go
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.

[Set]: https://godoc.org/github.com/zeebo/errs/errdata#Set
[Get]: https://godoc.org/github.com/zeebo/errs/errdata#Get