File: error_test.go

package info (click to toggle)
golang-github-bugsnag-bugsnag-go 1.0.5%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 456 kB
  • sloc: makefile: 9
file content (114 lines) | stat: -rw-r--r-- 1,930 bytes parent folder | download | duplicates (2)
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package errors

import (
	"bytes"
	"fmt"
	"io"
	"runtime/debug"
	"testing"
)

func TestStackFormatMatches(t *testing.T) {

	defer func() {
		err := recover()
		if err != 'a' {
			t.Fatal(err)
		}

		bs := [][]byte{Errorf("hi").Stack(), debug.Stack()}

		// Ignore the first line (as it contains the PC of the .Stack() call)
		bs[0] = bytes.SplitN(bs[0], []byte("\n"), 2)[1]
		bs[1] = bytes.SplitN(bs[1], []byte("\n"), 2)[1]

		if bytes.Compare(bs[0], bs[1]) != 0 {
			t.Errorf("Stack didn't match")
			t.Errorf("%s", bs[0])
			t.Errorf("%s", bs[1])
		}
	}()

	a()
}

func TestSkipWorks(t *testing.T) {

	defer func() {
		err := recover()
		if err != 'a' {
			t.Fatal(err)
		}

		bs := [][]byte{New("hi", 2).Stack(), debug.Stack()}

		if !bytes.HasSuffix(bs[1], bs[0]) {
			t.Errorf("Stack didn't match")
			t.Errorf("%s", bs[0])
			t.Errorf("%s", bs[1])
		}
	}()

	a()
}

func TestNewError(t *testing.T) {

	e := func() error {
		return New("hi", 1)
	}()

	if e.Error() != "hi" {
		t.Errorf("Constructor with a string failed")
	}

	if New(fmt.Errorf("yo"), 0).Error() != "yo" {
		t.Errorf("Constructor with an error failed")
	}

	if New(e, 0) != e {
		t.Errorf("Constructor with an Error failed")
	}

	if New(nil, 0).Error() != "<nil>" {
		t.Errorf("Constructor with nil failed")
	}
}

func ExampleErrorf(x int) (int, error) {
	if x%2 == 1 {
		return 0, Errorf("can only halve even numbers, got %d", x)
	}
	return x / 2, nil
}

func ExampleNewError() (error, error) {
	// Wrap io.EOF with the current stack-trace and return it
	return nil, New(io.EOF, 0)
}

func ExampleNewError_skip() {
	defer func() {
		if err := recover(); err != nil {
			// skip 1 frame (the deferred function) and then return the wrapped err
			err = New(err, 1)
		}
	}()
}

func ExampleError_Stack(err Error) {
	fmt.Printf("Error: %s\n%s", err.Error(), err.Stack())
}

func a() error {
	b(5)
	return nil
}

func b(i int) {
	c()
}

func c() {
	panic('a')
}