-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_stacktrace_test.go
More file actions
63 lines (50 loc) · 1.55 KB
/
example_stacktrace_test.go
File metadata and controls
63 lines (50 loc) · 1.55 KB
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
package errors_test
import (
"fmt"
"github.com/upfluence/errors"
)
func ExampleWithStack() {
// Simulate an error from an external library
externalErr := fmt.Errorf("external library error")
// Add stack trace at current location
err := errors.WithStack(externalErr)
fmt.Println(err)
// Output: external library error
}
// Result represents a simple computation result
type Result struct {
Value int
}
// mockCompute simulates an external library function
func mockCompute(input int) (Result, error) {
if input < 0 {
return Result{}, fmt.Errorf("negative input not allowed")
}
return Result{Value: input * 2}, nil
}
func ExampleWithStack2() {
// Demonstrates using WithStack2 to add stack traces inline while returning values
compute := func(input int) (Result, error) {
// WithStack2 adds stack trace in a single line
return errors.WithStack2(mockCompute(input))
}
// Success case - error is nil
result, err := compute(5)
fmt.Printf("Result: %+v, Error: %v\n", result, err)
// Error case - error gets stack trace added
result, err = compute(-1)
fmt.Printf("Result: %+v, Error: %v\n", result, err)
// Output:
// Result: {Value:10}, Error: <nil>
// Result: {Value:0}, Error: negative input not allowed
}
func ExampleWithFrame() {
// This helper function wraps errors with the caller's location
wrapError := func(err error) error {
// Skip 1 frame to capture the caller's location instead of this function
return errors.WithFrame(err, 1)
}
err := wrapError(fmt.Errorf("original error"))
fmt.Println(err)
// Output: original error
}