-
Notifications
You must be signed in to change notification settings - Fork 7
Description
Returning a typed nil from NewHTTPError causes err != nil to be true, leading to panics
Context
In the codebase, we have:
func (m *mongoPubSub) Publish(ctx context.Context, _ types.RealmID, tenant string, event EventMessage) error {
// ...
return types.NewHTTPError(http.StatusInternalServerError, err)
}
The NewHTTPError function is defined as:
func NewHTTPError(code int, e error) *HTTPError {
if e == nil {
return nil
}
// ...
}
So, when e is nil, NewHTTPError returns a *HTTPError that is nil (typed nil pointer).
However, when Publish returns this value, it is assigned to an error interface in the caller:
err := s.inner.Publish(ctx, realm, tenant, event)
return otel.RecordOutcome(err, span)
Problem
- Inside
Publish,erroris a*types.HTTPErrorand is<nil>. - When returned, it is assigned to an
errorinterface, which now has a non-nil type (*types.HTTPError) but a nil value. - This means
err != nilevaluates totrue, even though the value isnil. - This leads to code like
err.Error()panicking, since it tries to call a method on a nil pointer.
Solution:
Handle Mongo similar to GCP:
func (m *mongoPubSub) Publish(ctx context.Context, _ types.RealmID, tenant string, event EventMessage) error {
// ...
_, err = collection.InsertOne(ctx, me)
if err != nil {
return types.NewHTTPError(http.StatusInternalServerError, err)
}
return nil
}
@Imperiopolis, what do you think?