Skip to content

Commit 962cb00

Browse files
committed
Fix an issue when the error is nil but is different than nil
Signed-off-by: Bogdan Drutu <[email protected]>
1 parent 69ff46b commit 962cb00

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

receiver/receiverhelper/obsreport.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ package receiverhelper // import "go.opentelemetry.io/collector/receiver/receive
77

88
import (
99
"context"
10+
"reflect"
1011

1112
"go.opentelemetry.io/otel/attribute"
1213
"go.opentelemetry.io/otel/codes"
@@ -186,7 +187,7 @@ func (rec *ObsReport) endOp(
186187
attribute.Int64(acceptedItemsKey, int64(numAccepted)),
187188
attribute.Int64(refusedItemsKey, int64(numRefused)),
188189
)
189-
if err != nil {
190+
if !isErrorNil(err) {
190191
span.SetStatus(codes.Error, err.Error())
191192
}
192193
}
@@ -210,3 +211,12 @@ func (rec *ObsReport) recordMetrics(receiverCtx context.Context, signal pipeline
210211
acceptedMeasure.Add(receiverCtx, int64(numAccepted), metric.WithAttributes(rec.otelAttrs...))
211212
refusedMeasure.Add(receiverCtx, int64(numRefused), metric.WithAttributes(rec.otelAttrs...))
212213
}
214+
215+
// Correctly checks for nil, even in case of https://go.dev/doc/faq#nil_error.
216+
func isErrorNil(err error) bool {
217+
if err == nil {
218+
return true
219+
}
220+
val := reflect.ValueOf(err)
221+
return val.Kind() == reflect.Ptr && val.IsNil()
222+
}

receiver/receiverhelper/obsreport_test.go

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -296,10 +296,32 @@ func TestCheckReceiverLogsViews(t *testing.T) {
296296
assert.Error(t, tt.CheckReceiverLogs(transport, 0, 7))
297297
}
298298

299+
type myError struct {
300+
error
301+
}
302+
303+
func returnsError(b bool) error {
304+
var p *myError
305+
if b {
306+
p = &myError{error: errors.New("my error")}
307+
}
308+
return p // Will always return a non-nil error.
309+
}
310+
311+
func TestIsErrorNil(t *testing.T) {
312+
assert.True(t, isErrorNil(nil))
313+
assert.False(t, isErrorNil(returnsError(true)))
314+
// nolint
315+
assert.NotNil(t, returnsError(true) == nil)
316+
assert.True(t, isErrorNil(returnsError(false)))
317+
// nolint
318+
assert.False(t, returnsError(false) == nil)
319+
assert.False(t, isErrorNil(myError{error: errors.New("my error")}))
320+
}
321+
299322
func testTelemetry(t *testing.T, id component.ID, testFunc func(t *testing.T, tt componenttest.TestTelemetry)) {
300323
tt, err := componenttest.SetupTelemetry(id)
301324
require.NoError(t, err)
302325
t.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })
303-
304326
testFunc(t, tt)
305327
}

0 commit comments

Comments
 (0)