Commit 8e6e163f authored by Kirill Smelkov's avatar Kirill Smelkov

xerr.Context: Switch to constructing adjusted error from fmt.Errorf -> errors.WithMessage

This way original error can still be retrieved via errors.Cause()
parent c93b6a4b
......@@ -20,6 +20,8 @@ package xerr
import (
"fmt"
"github.com/pkg/errors"
)
// error merging multiple errors (e.g. after collecting them from several parallel workers)
......@@ -113,15 +115,17 @@ func First(errv ...error) error {
//
// which is equivalent to
//
// import "github.com/pkg/errors"
//
// ..., myerr := f()
// if myerr != nil {
// myerr = fmt.Errorf("%s: %s", "while doing something", myerr)
// myerr = errors.WithMessage(myerr, "while doing something")
// }
func Context(errp *error, context string) {
if *errp == nil {
return
}
*errp = fmt.Errorf("%s: %s", context, *errp)
*errp = errors.WithMessage(*errp, context)
}
// Contextf provides formatted error context to be automatically added on error return
......@@ -131,7 +135,5 @@ func Contextf(errp *error, format string, argv ...interface{}) {
return
}
format += ": %s"
argv = append(argv, *errp)
*errp = fmt.Errorf(format, argv...)
*errp = errors.WithMessage(*errp, fmt.Sprintf(format, argv...))
}
......@@ -21,6 +21,8 @@ import (
"errors"
"reflect"
"testing"
pkgerrors "github.com/pkg/errors"
)
func TestErrorv(t *testing.T) {
......@@ -144,13 +146,21 @@ func TestContext(t *testing.T) {
err := errors.New("an error")
e := test(err)
want := "test ctx: an error"
if e := test(err); !(e != nil && e.Error() == want) {
if !(e != nil && e.Error() == want) {
t.Errorf("Context(%v) -> %v ; want %v", err, e, want)
}
if ec := pkgerrors.Cause(e); ec != err {
t.Errorf("Context(%v) -> %v -> cause %v ; want %v", err, e, ec, err)
}
e = testf(err)
want = `testf ctx 123 "hello": an error`
if e := testf(err); !(e != nil && e.Error() == want) {
if !(e != nil && e.Error() == want) {
t.Errorf("Contextf(%v) -> %v ; want %v", err, e, want)
}
if ec := pkgerrors.Cause(e); ec != err {
t.Errorf("Contextf(%v) -> %v -> cause %v ; want %v", err, e, ec, err)
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment