mirror of
https://github.com/pkg/errors.git
synced 2025-05-03 14:09:43 +00:00
* Introduce Stacktrace and Frame This PR is a continuation of a series aimed at exposing the stack trace information embedded in each error value. The secondary effect is to deprecated the `Fprintf` helper. Taking cues from from @chrishines' `stack` package this PR introduces a new interface `Stacktrace() []Frame` and a `Frame` type, similar in function to the `runtime.Frame` type (although lacking its iterator type). Each `Frame` implemnts `fmt.Formatter` allowing it to print itself. The older `Location` interface is still supported but also deprecated.
88 lines
1.7 KiB
Go
88 lines
1.7 KiB
Go
package errors_test
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
|
|
"github.com/pkg/errors"
|
|
)
|
|
|
|
func ExampleNew() {
|
|
err := errors.New("whoops")
|
|
fmt.Println(err)
|
|
|
|
// Output: whoops
|
|
}
|
|
|
|
func ExampleNew_fprint() {
|
|
err := errors.New("whoops")
|
|
errors.Fprint(os.Stdout, err)
|
|
|
|
// Output: github.com/pkg/errors/example_test.go:18: whoops
|
|
}
|
|
|
|
func ExampleWrap() {
|
|
cause := errors.New("whoops")
|
|
err := errors.Wrap(cause, "oh noes")
|
|
fmt.Println(err)
|
|
|
|
// Output: oh noes: whoops
|
|
}
|
|
|
|
func fn() error {
|
|
e1 := errors.New("error")
|
|
e2 := errors.Wrap(e1, "inner")
|
|
e3 := errors.Wrap(e2, "middle")
|
|
return errors.Wrap(e3, "outer")
|
|
}
|
|
|
|
func ExampleCause() {
|
|
err := fn()
|
|
fmt.Println(err)
|
|
fmt.Println(errors.Cause(err))
|
|
|
|
// Output: outer: middle: inner: error
|
|
// error
|
|
}
|
|
|
|
func ExampleFprint() {
|
|
err := fn()
|
|
errors.Fprint(os.Stdout, err)
|
|
|
|
// Output: github.com/pkg/errors/example_test.go:36: outer
|
|
// github.com/pkg/errors/example_test.go:35: middle
|
|
// github.com/pkg/errors/example_test.go:34: inner
|
|
// github.com/pkg/errors/example_test.go:33: error
|
|
}
|
|
|
|
func ExampleWrapf() {
|
|
cause := errors.New("whoops")
|
|
err := errors.Wrapf(cause, "oh noes #%d", 2)
|
|
fmt.Println(err)
|
|
|
|
// Output: oh noes #2: whoops
|
|
}
|
|
|
|
func ExampleErrorf() {
|
|
err := errors.Errorf("whoops: %s", "foo")
|
|
errors.Fprint(os.Stdout, err)
|
|
|
|
// Output: github.com/pkg/errors/example_test.go:67: whoops: foo
|
|
}
|
|
|
|
func ExampleError_Stacktrace() {
|
|
type Stacktrace interface {
|
|
Stacktrace() []errors.Frame
|
|
}
|
|
|
|
err, ok := errors.Cause(fn()).(Stacktrace)
|
|
if !ok {
|
|
panic("oops, err does not implement Stacktrace")
|
|
}
|
|
|
|
st := err.Stacktrace()
|
|
fmt.Printf("%+v", st[0:2]) // top two framces
|
|
|
|
// Output: [github.com/pkg/errors/example_test.go:33 github.com/pkg/errors/example_test.go:78]
|
|
}
|