-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
examples_test.go
83 lines (67 loc) · 1.58 KB
/
examples_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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright (c) 2019, Roel Schut. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package errors
import (
"encoding/json"
"errors"
"fmt"
)
func ExampleNew() {
doSomething := func() error {
return New("something happened")
}
err := doSomething()
fmt.Println(err)
// Output: something happened
}
func ExampleMsg() {
const ErrSomethingHappened Msg = "something happened"
doSomething := func() error {
return New(ErrSomethingHappened)
}
err := doSomething()
fmt.Println(err)
// Output: something happened
}
func ExampleAppend() {
type Result struct{}
unmarshal := func() (*Result, error) {
dest := new(Result)
err := json.Unmarshal([]byte("invalid"), &dest) // this wil result in an error
return dest, WithStack(err)
}
closeSomething := func() error {
return errors.New("some error occurred while closing something")
}
doSomething := func() (err error) {
defer AppendFunc(&err, closeSomething)
_, err = unmarshal()
if err != nil {
return err
}
return nil
}
err := doSomething()
fmt.Println(err)
// Output:
// multiple errors occurred:
// [1/2] invalid character 'i' looking for beginning of value;
// [2/2] some error occurred while closing something
}
func ExampleCatchPanic() {
var err error
done := make(chan struct{})
go func() {
defer close(done)
defer CatchPanic(&err)
err = New("first error")
panic("something bad happened")
}()
<-done
fmt.Println(err)
// Output:
// multiple errors occurred:
// [1/2] first error;
// [2/2] panic: something bad happened
}