Skip to content

Instantly share code, notes, and snippets.

@akm
Last active November 23, 2023 13:07
Show Gist options
  • Save akm/094886da8f6ef8b119b7019d9e08f0b8 to your computer and use it in GitHub Desktop.
Save akm/094886da8f6ef8b119b7019d9e08f0b8 to your computer and use it in GitHub Desktop.
Stacktrace examples
package main
import (
"fmt"
"github.com/friendsofgo/errors"
)
func main() {
err := foo1()
fmt.Printf("github.com/friendsofgo/errors v: %v\n", err)
fmt.Printf("github.com/friendsofgo/errors plus v: %+v\n", err)
}
func foo1() error {
return foo2()
}
func foo2() error {
return foo3()
}
func foo3() error {
err := fmt.Errorf("Error1")
return errors.Wrap(err, "error on foo3")
}
/*
go run .
github.com/friendsofgo/errors v: error on foo3: Error1
github.com/friendsofgo/errors plus v: Error1
error on foo3
main.foo3
/path/to/friendsofgo_errors_example/main.go:25
main.foo2
/path/to/friendsofgo_errors_example/main.go:20
main.foo1
/path/to/friendsofgo_errors_example/main.go:16
main.main
/path/to/friendsofgo_errors_example/main.go:10
runtime.main
$HOME/.asdf/installs/golang/1.21.3/go/src/runtime/proc.go:267
runtime.goexit
$HOME/.asdf/installs/golang/1.21.3/go/src/runtime/asm_arm64.s:1197
*/
package main
import (
"fmt"
"github.com/pkg/errors"
)
func main() {
err := foo1()
fmt.Printf("github.com/pkg/errors v: %v\n", err)
fmt.Printf("github.com/pkg/errors plus v: %+v\n", err)
}
func foo1() error {
return foo2()
}
func foo2() error {
return foo3()
}
func foo3() error {
err := fmt.Errorf("Error1")
// return errors.Errorf("error on foo3: %w", err)
return errors.Wrap(err, "error on foo3: %w")
}
/*
$ go run .
github.com/pkg/errors v: error on foo3: %w: Error1
github.com/pkg/errors plus v: Error1
error on foo3: %w
main.foo3
/path/to/pkg_errors_example/main.go:26
main.foo2
/path/to/pkg_errors_example/main.go:20
main.foo1
/path/to/pkg_errors_example/main.go:16
main.main
/path/to/pkg_errors_example/main.go:10
runtime.main
$HOME/.asdf/installs/golang/1.21.3/go/src/runtime/proc.go:267
runtime.goexit
$HOME/.asdf/installs/golang/1.21.3/go/src/runtime/asm_arm64.s:1197
*/
package main
import (
"fmt"
"golang.org/x/xerrors"
)
func main() {
err := foo1()
fmt.Printf("golang.org/x/xerrors v: %v\n", err)
fmt.Printf("golang.org/x/xerrors plus v: %+v\n", err)
}
func foo1() error {
return foo2()
}
func foo2() error {
return foo3()
}
func foo3() error {
err := fmt.Errorf("Error1")
return xerrors.Errorf("error on foo3: %w", err)
}
/*
$ go run .
golang.org/x/xerrors v: error on foo3: Error1
golang.org/x/xerrors plus v: error on foo3:
main.foo3
/path/to/xerrors_example/main.go:26
- Error1
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment