Skip to content

Commit

Permalink
Fix an issue when the error is nil but is different than nil
Browse files Browse the repository at this point in the history
Signed-off-by: Bogdan Drutu <bogdandrutu@gmail.com>
  • Loading branch information
bogdandrutu committed Oct 3, 2024
1 parent 69ff46b commit 962cb00
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
12 changes: 11 additions & 1 deletion receiver/receiverhelper/obsreport.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package receiverhelper // import "go.opentelemetry.io/collector/receiver/receive

import (
"context"
"reflect"

"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
Expand Down Expand Up @@ -186,7 +187,7 @@ func (rec *ObsReport) endOp(
attribute.Int64(acceptedItemsKey, int64(numAccepted)),
attribute.Int64(refusedItemsKey, int64(numRefused)),
)
if err != nil {
if !isErrorNil(err) {
span.SetStatus(codes.Error, err.Error())
}
}
Expand All @@ -210,3 +211,12 @@ func (rec *ObsReport) recordMetrics(receiverCtx context.Context, signal pipeline
acceptedMeasure.Add(receiverCtx, int64(numAccepted), metric.WithAttributes(rec.otelAttrs...))
refusedMeasure.Add(receiverCtx, int64(numRefused), metric.WithAttributes(rec.otelAttrs...))
}

// Correctly checks for nil, even in case of https://go.dev/doc/faq#nil_error.
func isErrorNil(err error) bool {
if err == nil {
return true
}
val := reflect.ValueOf(err)
return val.Kind() == reflect.Ptr && val.IsNil()
}
24 changes: 23 additions & 1 deletion receiver/receiverhelper/obsreport_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -296,10 +296,32 @@ func TestCheckReceiverLogsViews(t *testing.T) {
assert.Error(t, tt.CheckReceiverLogs(transport, 0, 7))
}

type myError struct {
error
}

func returnsError(b bool) error {
var p *myError
if b {
p = &myError{error: errors.New("my error")}
}
return p // Will always return a non-nil error.
}

func TestIsErrorNil(t *testing.T) {
assert.True(t, isErrorNil(nil))
assert.False(t, isErrorNil(returnsError(true)))
// nolint
assert.NotNil(t, returnsError(true) == nil)
assert.True(t, isErrorNil(returnsError(false)))
// nolint
assert.False(t, returnsError(false) == nil)
assert.False(t, isErrorNil(myError{error: errors.New("my error")}))
}

func testTelemetry(t *testing.T, id component.ID, testFunc func(t *testing.T, tt componenttest.TestTelemetry)) {
tt, err := componenttest.SetupTelemetry(id)
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })

testFunc(t, tt)
}

0 comments on commit 962cb00

Please sign in to comment.