Skip to content

Commit

Permalink
Fix error in werror.Wrap and werror.WrapWithMsg (#128)
Browse files Browse the repository at this point in the history
  • Loading branch information
lquerel authored Mar 28, 2023
1 parent 04f2385 commit 31c385e
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
37 changes: 35 additions & 2 deletions pkg/werror/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,15 @@ func (w Wrapper) Error() string {

if w.context != nil {
msg.WriteString("{")
i := 0
for k, v := range w.context {
if i > 0 {
msg.WriteString(", ")
}
msg.WriteString(k)
msg.WriteString("=")
msg.WriteString(fmt.Sprintf("%v", v))
i++
}
msg.WriteString("}")
}
Expand Down Expand Up @@ -87,7 +92,20 @@ func (w Wrapper) Function() string {

// Wrap wraps the given error with the current file, line, and function.
func Wrap(err error) error {
return WrapWithContext(err, nil)
if err == nil {
return nil
}

pc, file, line, _ := runtime.Caller(1)
fn := runtime.FuncForPC(pc)

return Wrapper{
err: err,
file: file,
line: line,
function: fn.Name(),
context: nil,
}
}

// WrapWithContext wraps the given error with the current file, line, function,
Expand All @@ -114,5 +132,20 @@ func WrapWithMsg(err error, msg string) error {
return nil
}

return WrapWithContext(err, map[string]interface{}{"msg": msg})
context := map[string]interface{}{"msg": msg}

if err == nil {
return nil
}

pc, file, line, _ := runtime.Caller(1)
fn := runtime.FuncForPC(pc)

return Wrapper{
err: err,
file: file,
line: line,
function: fn.Name(),
context: context,
}
}
4 changes: 2 additions & 2 deletions pkg/werror/error_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ func TestWError(t *testing.T) {
t.Parallel()

err := Level1a()
require.Equal(t, "github.com/f5/otel-arrow-adapter/pkg/werror.Wrap:90->github.com/f5/otel-arrow-adapter/pkg/werror.Level2:48{id=1}->test error", err.Error())
require.Equal(t, "github.com/f5/otel-arrow-adapter/pkg/werror.Level1a:40->github.com/f5/otel-arrow-adapter/pkg/werror.Level2:48{id=1}->test error", err.Error())

err = Level1b()
require.Equal(t, "github.com/f5/otel-arrow-adapter/pkg/werror.Wrap:90->github.com/f5/otel-arrow-adapter/pkg/werror.Level2:48{id=2}->test error", err.Error())
require.Equal(t, "github.com/f5/otel-arrow-adapter/pkg/werror.Level1b:44->github.com/f5/otel-arrow-adapter/pkg/werror.Level2:48{id=2}->test error", err.Error())
}

var ErrTest = errors.New("test error")
Expand Down

0 comments on commit 31c385e

Please sign in to comment.