|
| 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