Skip to content

Commit 094e1f3

Browse files
authored
chore(android): Add docs for using the Android SDK within a shared environment (#11089)
* chore(android): Add docs for using the Android SDK within a shared environment * Address PR feedback * Update shared-environments.mdx
1 parent 5df1ee1 commit 094e1f3

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
---
2+
title: Using Sentry within an SDK
3+
description: "Learn how to use the Sentry SDK within a shared environment, e.g. another SDK."
4+
sidebar_order: 2000
5+
---
6+
7+
<Note>
8+
9+
Using the Sentry SDK within another SDK is [discouraged](https://docs.sentry.io/platforms/). This can lead to unexpected behaviour and potential data leakage. If you need to use Sentry within another SDK, please follow the best practices outlined below.
10+
11+
</Note>
12+
13+
<Note>
14+
15+
When setting up Sentry inside a library, the consuming app could use the Sentry SDK as well, thus you should **not use `Sentry.init()`**, as this will pollute the global state.
16+
17+
</Note>
18+
19+
In order to not conflict with other Sentry instances, you should use the `Hub` API to create a new instance of Sentry.
20+
The Hub API works the same way as the global Sentry instance, but it is not global and can be used within your component. If you want to capture uncaught exceptions, you can use the `UncaughtExceptionHandlerIntegration` to capture them. As this will capture all uncaught exceptions within an app, you should use the `BeforeSendCallback` to only accept events that are relevant for your SDK.
21+
22+
```kotlin
23+
import io.sentry.Hub
24+
import io.sentry.SentryOptions
25+
import io.sentry.SentryOptions.BeforeSendCallback
26+
import io.sentry.UncaughtExceptionHandlerIntegration
27+
28+
val options = SentryOptions().apply {
29+
dsn = "___PUBLIC_DSN___"
30+
isEnableUncaughtExceptionHandler = true
31+
setBeforeSend { event, _ ->
32+
// as uncaught exceptions are captured globally,
33+
// you need to only accept events which are relevant
34+
if (isRelevantForMySdk(event.throwable)) {
35+
return@setBeforeSend event
36+
}
37+
// drop the event
38+
return@setBeforeSend null
39+
}
40+
41+
}
42+
43+
val hub = Hub(options)
44+
45+
val integration = UncaughtExceptionHandlerIntegration()
46+
options.addIntegration(integration)
47+
integration.register(hub, options)
48+
```
49+
50+
Once the Hub is configured, you can use it to capture events:
51+
52+
```kotlin
53+
hub.captureException(IllegalStateException("Example Exception"))
54+
```
55+
56+
If your SDK can be opened and closed multiple times, you should also close the Hub when you are done with it:
57+
58+
```kotlin
59+
hub.close()
60+
```

0 commit comments

Comments
 (0)