getsentry / getsentry/sentry-dotnet

Improve the `Contexts[".."] = string` pitfall

Open
#4,234 0 comments 0 reactions 0 assignees View on GitHub
.NET Improvement
Dominant language
C#
Stars
770
Forks
248
Avg merge
3d 4h
Merged PRs (30d)
49

Description

We have a pitfall on our API today through `Contexts`

That's because it takes `object`, which should be valid, but Sentry will error out with:

![Image](https://github.com/user-attachments/assets/ea5ecc0e-4550-46d8-9d6b-caa7bdf5813d)

That's because Sentry expects a complex object. A valid usage would be:

```csharp
SentrySdk.ConfigureScope(s => s.Contexts["key"] = new { Value = "value" });
```

As we've [documented here](https://docs.sentry.io/platforms/dotnet/enriching-events/context/#structured-context).

# Some ideas to improve this

### Roslyn analyzer

This is ideal IMO, we can warn in the IDE that Sentry expects an object there.

### Warn on console, if debug:true

If Debug=true, if the indexer is set with a common simple type like int/string/long, we print to the console that Sentry expects an object

### Docs

Note [on the docs](https://docs.sentry.io/platforms/dotnet/enriching-events/context/) that `Contexts` requires an object.

And since I spotted this pitfall when our customer was trying to set User, another idea:

We have docs for setting the user [User](https://docs.sentry.io/platforms/dotnet/enriching-events/identify-user/). Which always has `new User` in the examples. But, User is already set. So unless you'd like to **reset** the user value (clean all fields). Better examples would be:

```csharp
SentrySdk.ConfigureScope(scope => scope.User.Email = "john.doe@example.com");
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.