Select Git revision
error_formats_test.go
-
Cornel Rautenbach authoredCornel Rautenbach authored
error_formats_test.go 12.46 KiB
package errors_test
import (
"encoding/json"
"fmt"
"testing"
go_errors "errors"
pkg_errors "github.com/pkg/errors"
uf_errors "gitlab.com/uafrica/go-utils/errors"
)
//use this struct to define various types of errors to experiment with
type Test struct {
title string
err error
}
var tests []Test
//define the errors for testing
//in each case, the main error message is "<this is broken>"
//in some cases that is passed up and wrapped with more messages
//the tests use different combinations of go errors, fmt.Errorf(), github.com/pkg/errors and our own go-utils/errors library
//NOTE: I put all the new calls on new lines to report different line numbers in the stack...
func init() {
tests = []Test{
//a very simple go "errors.New()" error - does not have a stack
{title: "go.New(...)", err: go_errors.New("<this is broken>")},
//a fmt.Errorf() error - does not have a stack
{title: "fmt.Errorf(...)", err: fmt.Errorf("<this is broken>")},
//a better github.com/pkg/errors.New() error that includes the call stack
{title: "pkg.New(...)", err: pkg_errors.New("<this is broken>")},
//our own error type that always records the caller:
{title: "uafrica.New(...)", err: uf_errors.New("<this is broken>")},
//one can use pkg WithStack() to add a stack to an error that does not have a stack
{title: "pkg.WithStack(go.New(...))", err: pkg_errors.WithStack(
go_errors.New("<this is broken>"),
)},
//if you are ok with pkg's way to add a stack manually (I am not),
//then you could easily make this mistake to add a stack to an error that already has a stack
//by default pkg then prints two stacks and the rest of the error messages are after the last stack
//making it very hard to figure out what went wrong and where...
{title: "pkg.WithStack(pkg.New())", err: pkg_errors.WithStack(
pkg_errors.New("<this is broken>"),
)},
//one can also add a stack with our own errors,
//note that we always want an explanation which is just to enforce good practice:
{title: "uafrica.Wrapf(go.New(...))", err: uf_errors.Wrapf(
go_errors.New("<this is broken>"),
"<it is not working>",
)},
//and when we wrap an error that already has a stack, it will not duplicate,
//note that we always want an explanation which is just to enforce good practice:
{title: "uafrica.Wrapf(pkg.New(...))", err: uf_errors.Wrapf(
pkg_errors.New("<this is broken>"),
"<it is not working>",
)},
//pkg can also wrap an error with a text explanation,
//but the synctax is annoying as one has to add the stack and the message separately