Using Sentry within an SDK

Learn how to use the Sentry SDK within a shared environment, e.g. another SDK.

Using the Sentry SDK within another SDK is discouraged. 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.

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.

In order to not conflict with other Sentry instances, you should use the Hub API to create a new instance of Sentry. 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.

Copied
import io.sentry.Hub
import io.sentry.SentryOptions
import io.sentry.SentryOptions.BeforeSendCallback
import io.sentry.UncaughtExceptionHandlerIntegration

val options = SentryOptions().apply {
    dsn = "https://examplePublicKey@o0.ingest.sentry.io/0"
    isEnableUncaughtExceptionHandler = true
    setBeforeSend { event, _ ->
        // as uncaught exceptions are captured globally,
        // you need to only accept events which are relevant
        if (isRelevantForMySdk(event.throwable)) {
            return@setBeforeSend event
        }
        // drop the event
        return@setBeforeSend null
    }

}

val hub = Hub(options)

val integration = UncaughtExceptionHandlerIntegration()
options.addIntegration(integration)
integration.register(hub, options)

Once the Hub is configured, you can use it to capture events:

Copied
hub.captureException(IllegalStateException("Example Exception"))

If your SDK can be opened and closed multiple times, you should also close the Hub when you are done with it:

Copied
hub.close()
Help improve this content
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").