-
Notifications
You must be signed in to change notification settings - Fork 1
/
example_test.go
45 lines (36 loc) · 1.08 KB
/
example_test.go
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
package guru_test
import (
"fmt"
"net/http"
"github.com/pkg/errors"
"github.com/teamwork/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
}