From cc2598aaa9b42a7f2573997739231005a7b3350b Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Wed, 18 Nov 2026 17:16:29 +0100 Subject: [PATCH 1/5] fix: Keep handling LinkageError where the SDK expects it ExceptionUtils.rethrowIfFatal rethrows LinkageError. At these sites a LinkageError is the expected failure: a native library that failed to load, a missing optional dependency, or a mismatched Compose or androidx version. Each one is narrowed to the types the guarded code throws, or catches LinkageError before a broad catch that calls rethrowIfFatal. The event processor loops in SentryClient handle a LinkageError like any other processor failure. Refs #5513 Refs JAVA-552 Co-Authored-By: Claude Opus 5.5 --- .../java/io/sentry/android/core/AppState.java | 5 ++- .../sentry/android/core/NdkIntegration.java | 6 ++- .../core/ViewHierarchyEventProcessor.java | 14 ++++++ .../gestures/SentryWindowCallback.java | 10 +++++ .../sentry/android/ndk/DebugImagesLoader.java | 13 ++++++ .../java/io/sentry/android/ndk/SentryNdk.java | 6 +-- .../java/io/sentry/android/replay/Windows.kt | 28 ++++++++++-- .../io/sentry/android/replay/util/Nodes.kt | 8 +++- .../viewhierarchy/ComposeViewHierarchyNode.kt | 42 +++++++++++++----- .../android/replay/WindowManagerSpyTest.kt | 32 ++++++++++++++ .../io/sentry/sqlite/SentrySQLiteDriver.kt | 29 ++++++++---- .../sentry/sqlite/SentrySQLiteDriverTest.kt | 31 +++++++++++++ .../io/sentry/compose/SentryComposeHelper.kt | 6 ++- .../SentryContextStorageProvider.java | 6 ++- sentry/src/main/java/io/sentry/Scopes.java | 13 ++++++ sentry/src/main/java/io/sentry/Sentry.java | 15 +++++++ .../src/main/java/io/sentry/SentryClient.java | 43 ++++++++++++++++++ .../main/java/io/sentry/SentryOptions.java | 4 +- .../profiling/ProfilingServiceLoader.java | 7 ++- .../main/java/io/sentry/util/LoadClass.java | 3 +- sentry/src/test/java/io/sentry/ScopesTest.kt | 28 ++++++++++++ .../test/java/io/sentry/SentryClientTest.kt | 24 ++++++++++ sentry/src/test/java/io/sentry/SentryTest.kt | 44 +++++++++++++++++++ .../test/java/io/sentry/util/LoadClassTest.kt | 11 +++++ 24 files changed, 390 insertions(+), 38 deletions(-) create mode 100644 sentry-android-replay/src/test/java/io/sentry/android/replay/WindowManagerSpyTest.kt diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AppState.java b/sentry-android-core/src/main/java/io/sentry/android/core/AppState.java index 24562e3aa49..85ed5f78ff0 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AppState.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AppState.java @@ -112,7 +112,8 @@ private void ensureLifecycleObserver(final @NotNull ILogger logger) { SentryLevel.WARNING, "androidx.lifecycle is not available, some features might not be properly working," + "e.g. Session Tracking, Network and System Events breadcrumbs, etc."); - } catch (Throwable e) { + } catch (LinkageError e) { + // androidx.lifecycle has an incompatible version logger.log(SentryLevel.ERROR, "AppState could not register lifecycle observer", e); } } @@ -124,7 +125,7 @@ private void addObserverInternal(final @NotNull ILogger logger) { if (observerRef != null) { ProcessLifecycleOwner.get().getLifecycle().addObserver(observerRef); } - } catch (Throwable e) { + } catch (LinkageError e) { // This is to handle a potential 'AbstractMethodError' gracefully. The error is triggered in // connection with conflicting dependencies of the androidx.lifecycle. // //See the issue here: https://github.com/getsentry/sentry-java/pull/2228 diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/NdkIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/NdkIntegration.java index f8c96b71459..acabb77d493 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/NdkIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/NdkIntegration.java @@ -88,7 +88,9 @@ public final void register(final @NotNull IScopes scopes, final @NotNull SentryO this.options .getLogger() .log(SentryLevel.ERROR, "Failed to invoke the SentryNdk.init method.", e); - } catch (Throwable e) { + } catch (ReflectiveOperationException e) { + // InvocationTargetException wraps whatever SentryNdk.init threw, such as an + // UnsatisfiedLinkError when the native library failed to load disableNdkIntegration(this.options); this.options.getLogger().log(SentryLevel.ERROR, "Failed to initialize SentryNdk.", e); } @@ -120,7 +122,7 @@ public void close() throws IOException { options .getLogger() .log(SentryLevel.ERROR, "Failed to invoke the SentryNdk.close method.", e); - } catch (Throwable e) { + } catch (ReflectiveOperationException e) { options.getLogger().log(SentryLevel.ERROR, "Failed to close SentryNdk.", e); } finally { disableNdkIntegration(this.options); diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/ViewHierarchyEventProcessor.java b/sentry-android-core/src/main/java/io/sentry/android/core/ViewHierarchyEventProcessor.java index 4004310a3ff..99fe0d98cd4 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/ViewHierarchyEventProcessor.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/ViewHierarchyEventProcessor.java @@ -189,7 +189,14 @@ public static ViewHierarchy snapshotViewHierarchy( try { viewHierarchy.set(snapshotViewHierarchy(decorView, exporters)); latch.countDown(); + } catch (LinkageError e) { + // The Compose exporter calls Compose internals, which may not match the app's + // Compose version + logger.log(SentryLevel.ERROR, "Failed to process view hierarchy.", e); } catch (Throwable t) { + // The snapshot calls into the app's own views, so we can't know what it throws. + // The event is sent without a view hierarchy. + ExceptionUtils.rethrowIfFatal(t); logger.log(SentryLevel.ERROR, "Failed to process view hierarchy.", t); } }); @@ -197,7 +204,14 @@ public static ViewHierarchy snapshotViewHierarchy( return viewHierarchy.get(); } } + } catch (LinkageError e) { + // The Compose exporter calls Compose internals, which may not match the app's Compose + // version + logger.log(SentryLevel.ERROR, "Failed to process view hierarchy.", e); } catch (Throwable t) { + // The snapshot calls into the app's own views, so we can't know what it throws. The event + // is sent without a view hierarchy. + ExceptionUtils.rethrowIfFatal(t); logger.log(SentryLevel.ERROR, "Failed to process view hierarchy.", t); } return null; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/internal/gestures/SentryWindowCallback.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/gestures/SentryWindowCallback.java index 612eb97946e..7a3e6b42302 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/internal/gestures/SentryWindowCallback.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/internal/gestures/SentryWindowCallback.java @@ -6,6 +6,7 @@ import io.sentry.SentryLevel; import io.sentry.SentryOptions; import io.sentry.SpanStatus; +import io.sentry.util.ExceptionUtils; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -56,7 +57,16 @@ public boolean dispatchTouchEvent(final @Nullable MotionEvent motionEvent) { final MotionEvent copy = motionEventObtainer.obtain(motionEvent); try { handleTouchEvent(copy); + } catch (LinkageError e) { + // The Compose gesture locator calls Compose internals, which may not match the app's + // Compose version + if (options != null) { + options.getLogger().log(SentryLevel.ERROR, "Error dispatching touch event", e); + } } catch (Throwable e) { + // Locating the touched view calls into the app's own views, so we can't know what it + // throws. The gesture is not recorded, and the touch still reaches the app. + ExceptionUtils.rethrowIfFatal(e); if (options != null) { options.getLogger().log(SentryLevel.ERROR, "Error dispatching touch event", e); } diff --git a/sentry-android-ndk/src/main/java/io/sentry/android/ndk/DebugImagesLoader.java b/sentry-android-ndk/src/main/java/io/sentry/android/ndk/DebugImagesLoader.java index 602981c1d01..af817abe722 100644 --- a/sentry-android-ndk/src/main/java/io/sentry/android/ndk/DebugImagesLoader.java +++ b/sentry-android-ndk/src/main/java/io/sentry/android/ndk/DebugImagesLoader.java @@ -8,6 +8,7 @@ import io.sentry.ndk.NativeModuleListLoader; import io.sentry.protocol.DebugImage; import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Objects; import java.util.ArrayList; import java.util.HashSet; @@ -71,7 +72,13 @@ public DebugImagesLoader( .getLogger() .log(SentryLevel.DEBUG, "Debug images loaded: %d", debugImages.size()); } + } catch (LinkageError e) { + // e.g. UnsatisfiedLinkError when the native library failed to load + options.getLogger().log(SentryLevel.ERROR, e, "Failed to load debug images."); } catch (Throwable e) { + // A JNI call into sentry-native, so we can't know what it throws. The event is sent + // without debug images. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, e, "Failed to load debug images."); } } @@ -172,7 +179,13 @@ public void clearDebugImages() { moduleListLoader.clearModuleList(); options.getLogger().log(SentryLevel.INFO, "Debug images cleared."); + } catch (LinkageError e) { + // e.g. UnsatisfiedLinkError when the native library failed to load + options.getLogger().log(SentryLevel.ERROR, e, "Failed to clear debug images."); } catch (Throwable e) { + // A JNI call into sentry-native, so we can't know what it throws. The cached list is + // cleared either way. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, e, "Failed to clear debug images."); } debugImages = null; diff --git a/sentry-android-ndk/src/main/java/io/sentry/android/ndk/SentryNdk.java b/sentry-android-ndk/src/main/java/io/sentry/android/ndk/SentryNdk.java index e2339ca911d..e88f1435ab1 100644 --- a/sentry-android-ndk/src/main/java/io/sentry/android/ndk/SentryNdk.java +++ b/sentry-android-ndk/src/main/java/io/sentry/android/ndk/SentryNdk.java @@ -25,9 +25,9 @@ private SentryNdk() {} try { //noinspection UnstableApiUsage io.sentry.ndk.SentryNdk.loadNativeLibraries(); - } catch (Throwable t) { - // ignored - // if loadLibrary() fails, the later init() will throw an exception anyway + } catch (LinkageError ignored) { + // e.g. UnsatisfiedLinkError. The later init() throws too, which disables the NDK + // integration. } finally { loadLibraryLatch.countDown(); } diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/Windows.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/Windows.kt index 4f8f6cabf58..d38653324f4 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/Windows.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/Windows.kt @@ -23,6 +23,7 @@ import android.util.Log import android.view.View import android.view.Window import io.sentry.util.AutoClosableReentrantLock +import io.sentry.util.ExceptionUtils import java.io.Closeable import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.atomic.AtomicBoolean @@ -53,7 +54,7 @@ internal object WindowSpy { lazy(NONE) { try { Class.forName("com.android.internal.policy.DecorView") - } catch (ignored: Throwable) { + } catch (ignored: ClassNotFoundException) { Log.d("WindowSpy", "Unexpected exception loading DecorView on API $SDK_INT", ignored) null } @@ -171,7 +172,7 @@ internal object WindowManagerSpy { val className = "android.view.WindowManagerGlobal" try { Class.forName(className) - } catch (ignored: Throwable) { + } catch (ignored: ClassNotFoundException) { Log.w("WindowManagerSpy", ignored) null } @@ -195,11 +196,30 @@ internal object WindowManagerSpy { mViewsField?.let { mViewsField -> @Suppress("UNCHECKED_CAST") val mViews = mViewsField[windowManagerInstance] as ArrayList - mViewsField[windowManagerInstance] = swap(mViews) + val swapped = swapSafely(swap, mViews) ?: return + mViewsField[windowManagerInstance] = swapped } } - } catch (ignored: Throwable) { + } catch (ignored: ReflectiveOperationException) { + Log.w("WindowManagerSpy", ignored) + } catch (ignored: ClassCastException) { + // mViews is not an ArrayList on this device Log.w("WindowManagerSpy", ignored) } } + + private fun swapSafely( + swap: (ArrayList) -> ArrayList, + mViews: ArrayList, + ): ArrayList? = + try { + swap(mViews) + } catch (@Suppress("TooGenericExceptionCaught") e: Throwable) { + // swap notifies the root view listeners about the existing views, and those run replay's + // recorders, so we can't know what they throw. mViews is left as it was, so replay doesn't + // learn about root views being added or removed. + ExceptionUtils.rethrowIfFatal(e) + Log.w("WindowManagerSpy", e) + null + } } diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/util/Nodes.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/util/Nodes.kt index 704260cf311..66372e7ba77 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/util/Nodes.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/util/Nodes.kt @@ -33,6 +33,7 @@ import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.layout.findRootCoordinates import androidx.compose.ui.node.LayoutNode import androidx.compose.ui.text.TextLayoutResult +import io.sentry.util.ExceptionUtils import kotlin.math.ceil import kotlin.math.floor import kotlin.math.roundToInt @@ -93,7 +94,7 @@ internal fun LayoutNode.findPainter(): Painter? { return try { modifier::class.java.getDeclaredField("painter").apply { isAccessible = true }.get(modifier) as? Painter - } catch (e: Throwable) { + } catch (_: ReflectiveOperationException) { null } } @@ -136,7 +137,12 @@ internal fun LayoutNode.findTextColor(): Color? { (modifier::class.java.getDeclaredField("color").apply { isAccessible = true }.get(modifier) as? ColorProducer) ?.invoke() + } catch (_: LinkageError) { + // older Compose versions don't have ColorProducer + null } catch (e: Throwable) { + // ColorProducer.invoke() runs the app's color lambda, so we can't know what it throws + ExceptionUtils.rethrowIfFatal(e) null } } diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/viewhierarchy/ComposeViewHierarchyNode.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/viewhierarchy/ComposeViewHierarchyNode.kt index 2e40144e2de..cf8b8c69eac 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/viewhierarchy/ComposeViewHierarchyNode.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/viewhierarchy/ComposeViewHierarchyNode.kt @@ -32,6 +32,7 @@ import io.sentry.android.replay.util.toRect import io.sentry.android.replay.viewhierarchy.ViewHierarchyNode.GenericViewHierarchyNode import io.sentry.android.replay.viewhierarchy.ViewHierarchyNode.ImageViewHierarchyNode import io.sentry.android.replay.viewhierarchy.ViewHierarchyNode.TextViewHierarchyNode +import io.sentry.util.ExceptionUtils import java.lang.ref.WeakReference import java.lang.reflect.Method @@ -45,7 +46,7 @@ internal object ComposeViewHierarchyNode { .java .getDeclaredMethod("getCollapsedSemantics\$ui_release") .apply { isAccessible = true } - } catch (_: Throwable) { + } catch (_: NoSuchMethodException) { // ignore, as this method may not be available } return@lazy null @@ -57,7 +58,7 @@ internal object ComposeViewHierarchyNode { internal fun retrieveSemanticsConfiguration(node: LayoutNode): SemanticsConfiguration? { return try { node.semanticsConfiguration - } catch (t: Throwable) { + } catch (t: NoSuchMethodError) { // for backwards compatibility // Jetpack Compose 1.8 or older if (getCollapsedSemanticsMethod != null) { @@ -128,16 +129,27 @@ internal object ComposeViewHierarchyNode { } val visibleRect = node.coordinates.boundsInWindow(_rootCoordinates?.get()) - val semantics: SemanticsConfiguration? + var semanticsFailure: Throwable? = null + val semantics: SemanticsConfiguration? = + try { + retrieveSemanticsConfiguration(node) + } catch (e: LinkageError) { + // an unsupported Compose version, which must not crash the app + semanticsFailure = e + null + } catch (t: Throwable) { + // semantics modifiers run app code, so we can't know what this throws + ExceptionUtils.rethrowIfFatal(t) + semanticsFailure = t + null + } - try { - semantics = retrieveSemanticsConfiguration(node) - } catch (t: Throwable) { + if (semanticsFailure != null) { if (!semanticsRetrievalErrorLogged) { semanticsRetrievalErrorLogged = true logger.log( SentryLevel.ERROR, - t, + semanticsFailure, """ Error retrieving semantics information from Compose tree. Most likely you're using an unsupported version of androidx.compose.ui:ui. The supported @@ -152,7 +164,7 @@ internal object ComposeViewHierarchyNode { // fail fast in our own sample/UI-test apps (see SentryReplayDebug), so regressions surface // as crashes instead of silently degrading masking if (SentryReplayDebug.failFast) { - throw t + throw semanticsFailure } // If we're unable to retrieve the semantics configuration @@ -284,13 +296,23 @@ internal object ComposeViewHierarchyNode { return false } + var traversalFailure: Throwable? = null try { val rootNode = (view as? Owner)?.root ?: return false rootNode.traverse(parent, isComposeRoot = true, options, logger) + } catch (e: LinkageError) { + // an unsupported Compose version, which must not crash the app + traversalFailure = e } catch (e: Throwable) { + // the traversal runs app code, so we can't know what it throws + ExceptionUtils.rethrowIfFatal(e) + traversalFailure = e + } + + if (traversalFailure != null) { logger.log( SentryLevel.ERROR, - e, + traversalFailure, """ Error traversing Compose tree. Most likely you're using an unsupported version of androidx.compose.ui:ui. The minimum supported version is 1.5.0. If it's a newer @@ -302,7 +324,7 @@ internal object ComposeViewHierarchyNode { // fail fast in our own sample/UI-test apps (see SentryReplayDebug), so regressions surface // as crashes instead of silently skipping the whole Compose subtree (i.e. not masking it) if (SentryReplayDebug.failFast) { - throw e + throw traversalFailure } return false } diff --git a/sentry-android-replay/src/test/java/io/sentry/android/replay/WindowManagerSpyTest.kt b/sentry-android-replay/src/test/java/io/sentry/android/replay/WindowManagerSpyTest.kt new file mode 100644 index 00000000000..dd6cd32c729 --- /dev/null +++ b/sentry-android-replay/src/test/java/io/sentry/android/replay/WindowManagerSpyTest.kt @@ -0,0 +1,32 @@ +package io.sentry.android.replay + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.google.common.truth.Truth.assertThat +import kotlin.test.Test +import kotlin.test.assertFailsWith +import org.junit.runner.RunWith +import org.robolectric.annotation.Config + +@RunWith(AndroidJUnit4::class) +@Config(sdk = [30]) +class WindowManagerSpyTest { + + @Test + fun `a swap that throws does not propagate`() { + var swapped = false + + WindowManagerSpy.swapWindowManagerGlobalMViews { + swapped = true + error("listener failed") + } + + assertThat(swapped).isTrue() + } + + @Test + fun `a swap that throws a fatal error rethrows it`() { + assertFailsWith { + WindowManagerSpy.swapWindowManagerGlobalMViews { throw OutOfMemoryError("listener") } + } + } +} diff --git a/sentry-android-sqlite/src/main/java/io/sentry/sqlite/SentrySQLiteDriver.kt b/sentry-android-sqlite/src/main/java/io/sentry/sqlite/SentrySQLiteDriver.kt index 28b661cd3e7..baf4c6d6430 100644 --- a/sentry-android-sqlite/src/main/java/io/sentry/sqlite/SentrySQLiteDriver.kt +++ b/sentry-android-sqlite/src/main/java/io/sentry/sqlite/SentrySQLiteDriver.kt @@ -4,6 +4,7 @@ import androidx.sqlite.SQLiteConnection import androidx.sqlite.SQLiteDriver import io.sentry.ScopesAdapter import io.sentry.SentryLevel +import io.sentry.util.ExceptionUtils import io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion /** @@ -53,19 +54,31 @@ public class SentrySQLiteDriver private constructor(private val delegate: SQLite // create() ensures delegate is unwrapped, so we don't need to protect against double-wrapping // the connection. SentrySQLiteConnection(connection, spans) + } catch (e: LinkageError) { + // androidx.sqlite is compileOnly, so the app's version may not match the SQLiteConnection + // that SentrySQLiteConnection implements. The connection is returned uninstrumented. + logInstrumentationFailure(e) + connection } catch (t: Throwable) { - ScopesAdapter.getInstance() - .options - .logger - .log( - SentryLevel.ERROR, - "Failed to instrument SQLite connection; returning uninstrumented connection.", - t, - ) + // Instrumenting must never stop the app from opening its database, so any other failure + // also returns the connection uninstrumented. + ExceptionUtils.rethrowIfFatal(t) + logInstrumentationFailure(t) connection } } + private fun logInstrumentationFailure(t: Throwable) { + ScopesAdapter.getInstance() + .options + .logger + .log( + SentryLevel.ERROR, + "Failed to instrument SQLite connection; returning uninstrumented connection.", + t, + ) + } + public companion object { /** diff --git a/sentry-android-sqlite/src/test/java/io/sentry/sqlite/SentrySQLiteDriverTest.kt b/sentry-android-sqlite/src/test/java/io/sentry/sqlite/SentrySQLiteDriverTest.kt index 5816f3d859c..86592c4576e 100644 --- a/sentry-android-sqlite/src/test/java/io/sentry/sqlite/SentrySQLiteDriverTest.kt +++ b/sentry-android-sqlite/src/test/java/io/sentry/sqlite/SentrySQLiteDriverTest.kt @@ -122,6 +122,37 @@ class SentrySQLiteDriverTest { } } + @Test + fun `open returns the unwrapped delegate if wrapping fails with a LinkageError`() { + val brokenScopes = mock() + val validOptions = SentryOptions().apply { dsn = "https://key@sentry.io/proj" } + whenever(brokenScopes.options) + .thenThrow(NoClassDefFoundError("androidx/sqlite/SQLiteConnection")) + .thenReturn(validOptions) + + Mockito.mockStatic(Sentry::class.java).use { mockedSentry -> + mockedSentry.`when` { Sentry.getCurrentScopes() }.thenReturn(brokenScopes) + + val driver = fixture.getSut("myapp.db") + val result = driver.open("myapp.db") + + assertSame(fixture.mockConnection, result) + } + } + + @Test + fun `open rethrows a fatal error while wrapping`() { + val brokenScopes = mock() + whenever(brokenScopes.options).thenThrow(OutOfMemoryError("wrapping")) + + Mockito.mockStatic(Sentry::class.java).use { mockedSentry -> + mockedSentry.`when` { Sentry.getCurrentScopes() }.thenReturn(brokenScopes) + + val driver = fixture.getSut("myapp.db") + assertFailsWith { driver.open("myapp.db") } + } + } + // Smoke test ensuring all layers are properly wired up. @Test fun `full stack produces a span with correct metadata`() { diff --git a/sentry-compose/src/androidMain/kotlin/io/sentry/compose/SentryComposeHelper.kt b/sentry-compose/src/androidMain/kotlin/io/sentry/compose/SentryComposeHelper.kt index 10d02103ba1..39325bda05e 100644 --- a/sentry-compose/src/androidMain/kotlin/io/sentry/compose/SentryComposeHelper.kt +++ b/sentry-compose/src/androidMain/kotlin/io/sentry/compose/SentryComposeHelper.kt @@ -35,8 +35,10 @@ internal class SentryComposeHelper(logger: ILogger) { val value = sentryTagElementField.get(modifier) return value as String? } - } catch (e: Throwable) { - // ignored + } catch (_: IllegalAccessException) { + // fall back to SemanticsModifier below + } catch (_: ClassCastException) { + // the tag is not a String in this Compose version } // Older versions use SemanticsModifier diff --git a/sentry-opentelemetry/sentry-opentelemetry-bootstrap/src/main/java/io/sentry/opentelemetry/SentryContextStorageProvider.java b/sentry-opentelemetry/sentry-opentelemetry-bootstrap/src/main/java/io/sentry/opentelemetry/SentryContextStorageProvider.java index 16599595866..45dd6026874 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-bootstrap/src/main/java/io/sentry/opentelemetry/SentryContextStorageProvider.java +++ b/sentry-opentelemetry/sentry-opentelemetry-bootstrap/src/main/java/io/sentry/opentelemetry/SentryContextStorageProvider.java @@ -2,6 +2,7 @@ import io.opentelemetry.context.ContextStorage; import io.opentelemetry.context.ContextStorageProvider; +import io.sentry.util.ExceptionUtils; import java.util.Iterator; import java.util.ServiceLoader; import org.jetbrains.annotations.NotNull; @@ -23,8 +24,11 @@ public ContextStorage get() { return contextStorageProvider.get(); } } + } catch (LinkageError ignored) { + // a provider needs a class that is missing or has an incompatible version, use fallback } catch (Throwable t) { - // ignore and use fallback + // Other providers are third-party code, so we can't know what they throw. Use fallback. + ExceptionUtils.rethrowIfFatal(t); } // using default / fallback storage diff --git a/sentry/src/main/java/io/sentry/Scopes.java b/sentry/src/main/java/io/sentry/Scopes.java index 75c263c4127..927b2b6f117 100644 --- a/sentry/src/main/java/io/sentry/Scopes.java +++ b/sentry/src/main/java/io/sentry/Scopes.java @@ -9,6 +9,7 @@ import io.sentry.metrics.MetricsApi; import io.sentry.protocol.*; import io.sentry.transport.RateLimiter; +import io.sentry.util.ExceptionUtils; import io.sentry.util.HintUtils; import io.sentry.util.Objects; import io.sentry.util.SpanUtils; @@ -417,7 +418,16 @@ public void close(final boolean isRestarting) { if (integration instanceof Closeable) { try { ((Closeable) integration).close(); + } catch (LinkageError e) { + // The integration needs an optional dependency that is missing or has an + // incompatible version. The remaining integrations are still closed. + getOptions() + .getLogger() + .log(SentryLevel.WARNING, "Failed to close the integration {}.", integration, e); } catch (Throwable e) { + // Integrations can be user-provided, so we can't know what they throw. The + // remaining integrations are still closed. + ExceptionUtils.rethrowIfFatal(e); getOptions() .getLogger() .log(SentryLevel.WARNING, "Failed to close the integration {}.", integration, e); @@ -476,6 +486,9 @@ public void close(final boolean isRestarting) { configureScope(ScopeType.ISOLATION, scope -> scope.getClient().close(isRestarting)); configureScope(ScopeType.GLOBAL, scope -> scope.getClient().close(isRestarting)); } catch (Throwable e) { + // A public API entry point: closing shuts down components that integrations and the app + // can replace, so we can't know what it throws. The remaining shutdown steps are skipped. + ExceptionUtils.rethrowIfFatal(e); getOptions().getLogger().log(SentryLevel.ERROR, "Error while closing the Scopes.", e); } } diff --git a/sentry/src/main/java/io/sentry/Sentry.java b/sentry/src/main/java/io/sentry/Sentry.java index ce286600477..7f7879864e5 100644 --- a/sentry/src/main/java/io/sentry/Sentry.java +++ b/sentry/src/main/java/io/sentry/Sentry.java @@ -21,6 +21,7 @@ import io.sentry.transport.NoOpEnvelopeCache; import io.sentry.util.AutoClosableReentrantLock; import io.sentry.util.DebugMetaPropertiesApplier; +import io.sentry.util.ExceptionUtils; import io.sentry.util.FileUtils; import io.sentry.util.InitUtil; import io.sentry.util.LoadClass; @@ -362,7 +363,21 @@ private static void init(final @NotNull SentryOptions options, final boolean glo for (final Integration integration : options.getIntegrations()) { try { integration.register(ScopesAdapter.getInstance(), options); + } catch (LinkageError e) { + // The integration needs an optional dependency that is missing or has an incompatible + // version. It is skipped and init continues. + options + .getLogger() + .log( + SentryLevel.WARNING, + "Failed to register the integration " + + integration.getClass().getName() + + ", a dependency it needs is missing or incompatible", + e); } catch (Throwable t) { + // Integrations can be user-provided, so we can't know what they throw. A failing + // integration is skipped and init continues. + ExceptionUtils.rethrowIfFatal(t); options .getLogger() .log( diff --git a/sentry/src/main/java/io/sentry/SentryClient.java b/sentry/src/main/java/io/sentry/SentryClient.java index b5027432625..ba279517584 100644 --- a/sentry/src/main/java/io/sentry/SentryClient.java +++ b/sentry/src/main/java/io/sentry/SentryClient.java @@ -20,6 +20,7 @@ import io.sentry.transport.ITransport; import io.sentry.transport.RateLimiter; import io.sentry.util.*; +import io.sentry.util.ExceptionUtils; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; @@ -494,6 +495,13 @@ private SentryEvent processEvent( event = processor.process(event, hint); } } catch (Throwable e) { + // Event processors come from integrations and the app, so we can't know what they throw. + // An SDK processor is skipped; any other processor's failure drops the event. + // A LinkageError means the processor needs an optional dependency that is missing or has an + // incompatible version, which is handled like any other failure. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } options .getLogger() .log( @@ -551,6 +559,13 @@ private SentryLogEvent processLogEvent( try { event = processor.process(event); } catch (Throwable e) { + // Event processors come from integrations and the app, so we can't know what they throw. + // An SDK processor is skipped; any other processor's failure drops the log. + // A LinkageError means the processor needs an optional dependency that is missing or has an + // incompatible version, which is handled like any other failure. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } options .getLogger() .log( @@ -588,6 +603,13 @@ private SentryMetricsEvent processMetricsEvent( try { event = processor.process(event, hint); } catch (Throwable e) { + // Event processors come from integrations and the app, so we can't know what they throw. + // An SDK processor is skipped; any other processor's failure drops the metric. + // A LinkageError means the processor needs an optional dependency that is missing or has an + // incompatible version, which is handled like any other failure. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } options .getLogger() .log( @@ -625,6 +647,13 @@ private SentryMetricsEvent processMetricsEvent( try { transaction = processor.process(transaction, hint); } catch (Throwable e) { + // Event processors come from integrations and the app, so we can't know what they throw. + // An SDK processor is skipped; any other processor's failure drops the transaction. + // A LinkageError means the processor needs an optional dependency that is missing or has an + // incompatible version, which is handled like any other failure. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } options .getLogger() .log( @@ -698,6 +727,13 @@ private SentryReplayEvent processReplayEvent( try { replayEvent = processor.process(replayEvent, hint); } catch (Throwable e) { + // Event processors come from integrations and the app, so we can't know what they throw. + // An SDK processor is skipped; any other processor's failure drops the replay segment. + // A LinkageError means the processor needs an optional dependency that is missing or has an + // incompatible version, which is handled like any other failure. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } options .getLogger() .log( @@ -738,6 +774,13 @@ private SentryEvent processFeedbackEvent( try { feedbackEvent = processor.process(feedbackEvent, hint); } catch (Throwable e) { + // Event processors come from integrations and the app, so we can't know what they throw. + // An SDK processor is skipped; any other processor's failure drops the feedback. + // A LinkageError means the processor needs an optional dependency that is missing or has an + // incompatible version, which is handled like any other failure. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } options .getLogger() .log( diff --git a/sentry/src/main/java/io/sentry/SentryOptions.java b/sentry/src/main/java/io/sentry/SentryOptions.java index 5ba97164a5e..60b1f3cd426 100644 --- a/sentry/src/main/java/io/sentry/SentryOptions.java +++ b/sentry/src/main/java/io/sentry/SentryOptions.java @@ -744,8 +744,8 @@ public void activate() { try { final Class clazz = Class.forName("io.sentry.spotlight.SpotlightIntegration"); integrations.add((Integration) clazz.getConstructor().newInstance()); - } catch (Throwable ignored) { - // SpotlightIntegration not available + } catch (ReflectiveOperationException | LinkageError ignored) { + // sentry-spotlight is missing or has an incompatible version } } } diff --git a/sentry/src/main/java/io/sentry/profiling/ProfilingServiceLoader.java b/sentry/src/main/java/io/sentry/profiling/ProfilingServiceLoader.java index cf86a13fc53..683eea8a866 100644 --- a/sentry/src/main/java/io/sentry/profiling/ProfilingServiceLoader.java +++ b/sentry/src/main/java/io/sentry/profiling/ProfilingServiceLoader.java @@ -9,6 +9,7 @@ import io.sentry.ScopesAdapter; import io.sentry.SentryLevel; import java.util.Iterator; +import java.util.ServiceConfigurationError; import java.util.ServiceLoader; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; @@ -38,7 +39,8 @@ public final class ProfilingServiceLoader { logger.log( SentryLevel.DEBUG, "No continuous profiler provider found, using NoOpContinuousProfiler"); return NoOpContinuousProfiler.getInstance(); - } catch (Throwable t) { + } catch (ServiceConfigurationError | LinkageError t) { + // The provider is broken, or async-profiler's native library failed to load logger.log( SentryLevel.ERROR, "Failed to load continuous profiler provider, using NoOpContinuousProfiler", @@ -68,7 +70,8 @@ public final class ProfilingServiceLoader { SentryLevel.DEBUG, "No profile converter provider found, using NoOpProfileConverter"); return NoOpProfileConverter.getInstance(); } - } catch (Throwable t) { + } catch (ServiceConfigurationError | LinkageError t) { + // The provider is broken, or a class it needs is missing logger.log( SentryLevel.ERROR, "Failed to load profile converter provider, using NoOpProfileConverter", diff --git a/sentry/src/main/java/io/sentry/util/LoadClass.java b/sentry/src/main/java/io/sentry/util/LoadClass.java index bf179fad459..aedd27a14be 100644 --- a/sentry/src/main/java/io/sentry/util/LoadClass.java +++ b/sentry/src/main/java/io/sentry/util/LoadClass.java @@ -41,7 +41,8 @@ public class LoadClass { if (logger != null) { logger.log(SentryLevel.ERROR, "Failed to load (UnsatisfiedLinkError) " + clazz, e); } - } catch (Throwable e) { + } catch (LinkageError e) { + // e.g. ExceptionInInitializerError, or NoClassDefFoundError for a dependency of the class if (logger != null) { logger.log(SentryLevel.ERROR, "Failed to initialize " + clazz, e); } diff --git a/sentry/src/test/java/io/sentry/ScopesTest.kt b/sentry/src/test/java/io/sentry/ScopesTest.kt index 15e1d82941d..c67c259c682 100644 --- a/sentry/src/test/java/io/sentry/ScopesTest.kt +++ b/sentry/src/test/java/io/sentry/ScopesTest.kt @@ -22,6 +22,7 @@ import io.sentry.test.createTestScopes import io.sentry.test.initForTest import io.sentry.util.HintUtils import io.sentry.util.StringUtils +import java.io.Closeable import java.io.File import java.nio.file.Files import java.util.Queue @@ -830,6 +831,33 @@ class ScopesTest { // endregion // region close tests + @Test + fun `when an integration's close throws a LinkageError, the other integrations are still closed`() { + val failing = mock(extraInterfaces = arrayOf(Closeable::class)) + doThrow(NoClassDefFoundError("missing")).whenever(failing as Closeable).close() + val next = mock(extraInterfaces = arrayOf(Closeable::class)) + val (sut) = + getEnabledScopes { + it.addIntegration(failing) + it.addIntegration(next) + } + + sut.close() + + verify(next as Closeable).close() + } + + @Test + fun `when an integration's close throws a fatal error, it propagates`() { + val failing = mock(extraInterfaces = arrayOf(Closeable::class)) + doThrow(OutOfMemoryError("close")).whenever(failing as Closeable).close() + val (sut) = getEnabledScopes { it.addIntegration(failing) } + + assertFailsWith { sut.close() } + // the scopes are closed again after the test + reset(failing) + } + @Test fun `when close is called on disabled client, do nothing`() { val (sut, mockClient) = getEnabledScopes() diff --git a/sentry/src/test/java/io/sentry/SentryClientTest.kt b/sentry/src/test/java/io/sentry/SentryClientTest.kt index c1e96f842b7..37451a3f95f 100644 --- a/sentry/src/test/java/io/sentry/SentryClientTest.kt +++ b/sentry/src/test/java/io/sentry/SentryClientTest.kt @@ -1274,6 +1274,30 @@ class SentryClientTest { verify(processor).process(eq(event), anyOrNull()) } + @Test + fun `when an event processor throws a fatal error, it propagates`() { + val processor = mock() + whenever(processor.process(any(), any())).thenThrow(StackOverflowError()) + fixture.sentryOptions.addEventProcessor(processor) + val sut = fixture.getSut() + + assertFailsWith { sut.captureEvent(SentryEvent()) } + } + + @Test + fun `when an SDK event processor throws a LinkageError, it is skipped and the event is sent`() { + // an SDK processor whose optional dependency is missing at runtime + val processor = mock() + whenever(processor.process(any(), any())) + .thenThrow(NoClassDefFoundError("androidx/Missing")) + fixture.sentryOptions.addEventProcessor(processor) + val sut = fixture.getSut() + + sut.captureEvent(SentryEvent()) + + verify(fixture.transport).send(any(), anyOrNull()) + } + @Test fun `when options have event processors, apply for transactions`() { val processor = mock() diff --git a/sentry/src/test/java/io/sentry/SentryTest.kt b/sentry/src/test/java/io/sentry/SentryTest.kt index 9fb60f6922f..3ceac1ffdaa 100644 --- a/sentry/src/test/java/io/sentry/SentryTest.kt +++ b/sentry/src/test/java/io/sentry/SentryTest.kt @@ -57,6 +57,7 @@ import org.mockito.kotlin.argThat import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.atLeastOnce import org.mockito.kotlin.check +import org.mockito.kotlin.doThrow import org.mockito.kotlin.eq import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock @@ -680,6 +681,49 @@ class SentryTest { verify(logger).log(eq(SentryLevel.ERROR), any(), eq(initException)) } + @Test + fun `init skips an integration whose dependency is missing and registers the rest`() { + val failing = mock() + doThrow(NoClassDefFoundError("missing")).whenever(failing).register(any(), any()) + val next = mock() + + initForTest { + it.dsn = dsn + it.addIntegration(failing) + it.addIntegration(next) + } + + verify(next).register(any(), any()) + } + + @Test + fun `init skips an integration that throws on register and registers the rest`() { + val failing = mock() + doThrow(IllegalStateException("register")).whenever(failing).register(any(), any()) + val next = mock() + + initForTest { + it.dsn = dsn + it.addIntegration(failing) + it.addIntegration(next) + } + + verify(next).register(any(), any()) + } + + @Test + fun `init rethrows a fatal error from an integration's register`() { + val failing = mock() + doThrow(OutOfMemoryError("register")).whenever(failing).register(any(), any()) + + assertThrows(OutOfMemoryError::class.java) { + initForTest { + it.dsn = dsn + it.addIntegration(failing) + } + } + } + @Test fun `overrides envelope cache if it's not set`() { var sentryOptions: SentryOptions? = null diff --git a/sentry/src/test/java/io/sentry/util/LoadClassTest.kt b/sentry/src/test/java/io/sentry/util/LoadClassTest.kt index f73c6edd16d..901b018a86e 100644 --- a/sentry/src/test/java/io/sentry/util/LoadClassTest.kt +++ b/sentry/src/test/java/io/sentry/util/LoadClassTest.kt @@ -74,6 +74,17 @@ class LoadClassTest { assertTrue(LoadClassInitFlag.initialized) } + + @Test + fun `loadClass returns null when the static initializer of the class throws`() { + assertNull(LoadClass().loadClass(LoadClassFailingInitProbe::class.java.name, null)) + } +} + +private object LoadClassFailingInitProbe { + init { + throw IllegalStateException("init") + } } private object IsClassAvailableNoInitFlag { From b7474985047c092d223343fc756c57e5c14bfcbb Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Wed, 18 Nov 2026 17:32:25 +0100 Subject: [PATCH 2/5] changelog Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index be7899e2dd6..9d34350ee63 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -102,6 +102,7 @@ - Nav3: Stop attributing errors and spans from an Activity or ViewPager2 page without a `SentryNavEffect` to the most recently visited Nav3 root ([#6483](https://github.com/getsentry/sentry-java/pull/6483)) - Android: Count deep sleep in breadcrumb, screenshot and view hierarchy debounce windows, so the first low-memory or battery breadcrumb after a long Doze is no longer dropped ([#6590](https://github.com/getsentry/sentry-java/pull/6590)) - Avoid duplicate serialization debug logs when calculating serialized object sizes ([#6255](https://github.com/getsentry/sentry-java/pull/6255)) +- Stop swallowing fatal errors such as `OutOfMemoryError` in the SDK code that loads native libraries and optional dependencies ([#6666](https://github.com/getsentry/sentry-java/pull/6666)) ### Dependencies From b8be6a770fac0a84032f0af1a3bc0001cfb31ded Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Wed, 18 Nov 2026 18:33:48 +0100 Subject: [PATCH 3/5] test: Remove the tests added for the LinkageError sites Refs #5513 Refs JAVA-552 Co-Authored-By: Claude Opus 5.5 --- .../android/replay/WindowManagerSpyTest.kt | 32 -------------- .../sentry/sqlite/SentrySQLiteDriverTest.kt | 31 ------------- sentry/src/test/java/io/sentry/ScopesTest.kt | 28 ------------ .../test/java/io/sentry/SentryClientTest.kt | 24 ---------- sentry/src/test/java/io/sentry/SentryTest.kt | 44 ------------------- .../test/java/io/sentry/util/LoadClassTest.kt | 11 ----- 6 files changed, 170 deletions(-) delete mode 100644 sentry-android-replay/src/test/java/io/sentry/android/replay/WindowManagerSpyTest.kt diff --git a/sentry-android-replay/src/test/java/io/sentry/android/replay/WindowManagerSpyTest.kt b/sentry-android-replay/src/test/java/io/sentry/android/replay/WindowManagerSpyTest.kt deleted file mode 100644 index dd6cd32c729..00000000000 --- a/sentry-android-replay/src/test/java/io/sentry/android/replay/WindowManagerSpyTest.kt +++ /dev/null @@ -1,32 +0,0 @@ -package io.sentry.android.replay - -import androidx.test.ext.junit.runners.AndroidJUnit4 -import com.google.common.truth.Truth.assertThat -import kotlin.test.Test -import kotlin.test.assertFailsWith -import org.junit.runner.RunWith -import org.robolectric.annotation.Config - -@RunWith(AndroidJUnit4::class) -@Config(sdk = [30]) -class WindowManagerSpyTest { - - @Test - fun `a swap that throws does not propagate`() { - var swapped = false - - WindowManagerSpy.swapWindowManagerGlobalMViews { - swapped = true - error("listener failed") - } - - assertThat(swapped).isTrue() - } - - @Test - fun `a swap that throws a fatal error rethrows it`() { - assertFailsWith { - WindowManagerSpy.swapWindowManagerGlobalMViews { throw OutOfMemoryError("listener") } - } - } -} diff --git a/sentry-android-sqlite/src/test/java/io/sentry/sqlite/SentrySQLiteDriverTest.kt b/sentry-android-sqlite/src/test/java/io/sentry/sqlite/SentrySQLiteDriverTest.kt index 86592c4576e..5816f3d859c 100644 --- a/sentry-android-sqlite/src/test/java/io/sentry/sqlite/SentrySQLiteDriverTest.kt +++ b/sentry-android-sqlite/src/test/java/io/sentry/sqlite/SentrySQLiteDriverTest.kt @@ -122,37 +122,6 @@ class SentrySQLiteDriverTest { } } - @Test - fun `open returns the unwrapped delegate if wrapping fails with a LinkageError`() { - val brokenScopes = mock() - val validOptions = SentryOptions().apply { dsn = "https://key@sentry.io/proj" } - whenever(brokenScopes.options) - .thenThrow(NoClassDefFoundError("androidx/sqlite/SQLiteConnection")) - .thenReturn(validOptions) - - Mockito.mockStatic(Sentry::class.java).use { mockedSentry -> - mockedSentry.`when` { Sentry.getCurrentScopes() }.thenReturn(brokenScopes) - - val driver = fixture.getSut("myapp.db") - val result = driver.open("myapp.db") - - assertSame(fixture.mockConnection, result) - } - } - - @Test - fun `open rethrows a fatal error while wrapping`() { - val brokenScopes = mock() - whenever(brokenScopes.options).thenThrow(OutOfMemoryError("wrapping")) - - Mockito.mockStatic(Sentry::class.java).use { mockedSentry -> - mockedSentry.`when` { Sentry.getCurrentScopes() }.thenReturn(brokenScopes) - - val driver = fixture.getSut("myapp.db") - assertFailsWith { driver.open("myapp.db") } - } - } - // Smoke test ensuring all layers are properly wired up. @Test fun `full stack produces a span with correct metadata`() { diff --git a/sentry/src/test/java/io/sentry/ScopesTest.kt b/sentry/src/test/java/io/sentry/ScopesTest.kt index c67c259c682..15e1d82941d 100644 --- a/sentry/src/test/java/io/sentry/ScopesTest.kt +++ b/sentry/src/test/java/io/sentry/ScopesTest.kt @@ -22,7 +22,6 @@ import io.sentry.test.createTestScopes import io.sentry.test.initForTest import io.sentry.util.HintUtils import io.sentry.util.StringUtils -import java.io.Closeable import java.io.File import java.nio.file.Files import java.util.Queue @@ -831,33 +830,6 @@ class ScopesTest { // endregion // region close tests - @Test - fun `when an integration's close throws a LinkageError, the other integrations are still closed`() { - val failing = mock(extraInterfaces = arrayOf(Closeable::class)) - doThrow(NoClassDefFoundError("missing")).whenever(failing as Closeable).close() - val next = mock(extraInterfaces = arrayOf(Closeable::class)) - val (sut) = - getEnabledScopes { - it.addIntegration(failing) - it.addIntegration(next) - } - - sut.close() - - verify(next as Closeable).close() - } - - @Test - fun `when an integration's close throws a fatal error, it propagates`() { - val failing = mock(extraInterfaces = arrayOf(Closeable::class)) - doThrow(OutOfMemoryError("close")).whenever(failing as Closeable).close() - val (sut) = getEnabledScopes { it.addIntegration(failing) } - - assertFailsWith { sut.close() } - // the scopes are closed again after the test - reset(failing) - } - @Test fun `when close is called on disabled client, do nothing`() { val (sut, mockClient) = getEnabledScopes() diff --git a/sentry/src/test/java/io/sentry/SentryClientTest.kt b/sentry/src/test/java/io/sentry/SentryClientTest.kt index 37451a3f95f..c1e96f842b7 100644 --- a/sentry/src/test/java/io/sentry/SentryClientTest.kt +++ b/sentry/src/test/java/io/sentry/SentryClientTest.kt @@ -1274,30 +1274,6 @@ class SentryClientTest { verify(processor).process(eq(event), anyOrNull()) } - @Test - fun `when an event processor throws a fatal error, it propagates`() { - val processor = mock() - whenever(processor.process(any(), any())).thenThrow(StackOverflowError()) - fixture.sentryOptions.addEventProcessor(processor) - val sut = fixture.getSut() - - assertFailsWith { sut.captureEvent(SentryEvent()) } - } - - @Test - fun `when an SDK event processor throws a LinkageError, it is skipped and the event is sent`() { - // an SDK processor whose optional dependency is missing at runtime - val processor = mock() - whenever(processor.process(any(), any())) - .thenThrow(NoClassDefFoundError("androidx/Missing")) - fixture.sentryOptions.addEventProcessor(processor) - val sut = fixture.getSut() - - sut.captureEvent(SentryEvent()) - - verify(fixture.transport).send(any(), anyOrNull()) - } - @Test fun `when options have event processors, apply for transactions`() { val processor = mock() diff --git a/sentry/src/test/java/io/sentry/SentryTest.kt b/sentry/src/test/java/io/sentry/SentryTest.kt index 3ceac1ffdaa..9fb60f6922f 100644 --- a/sentry/src/test/java/io/sentry/SentryTest.kt +++ b/sentry/src/test/java/io/sentry/SentryTest.kt @@ -57,7 +57,6 @@ import org.mockito.kotlin.argThat import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.atLeastOnce import org.mockito.kotlin.check -import org.mockito.kotlin.doThrow import org.mockito.kotlin.eq import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock @@ -681,49 +680,6 @@ class SentryTest { verify(logger).log(eq(SentryLevel.ERROR), any(), eq(initException)) } - @Test - fun `init skips an integration whose dependency is missing and registers the rest`() { - val failing = mock() - doThrow(NoClassDefFoundError("missing")).whenever(failing).register(any(), any()) - val next = mock() - - initForTest { - it.dsn = dsn - it.addIntegration(failing) - it.addIntegration(next) - } - - verify(next).register(any(), any()) - } - - @Test - fun `init skips an integration that throws on register and registers the rest`() { - val failing = mock() - doThrow(IllegalStateException("register")).whenever(failing).register(any(), any()) - val next = mock() - - initForTest { - it.dsn = dsn - it.addIntegration(failing) - it.addIntegration(next) - } - - verify(next).register(any(), any()) - } - - @Test - fun `init rethrows a fatal error from an integration's register`() { - val failing = mock() - doThrow(OutOfMemoryError("register")).whenever(failing).register(any(), any()) - - assertThrows(OutOfMemoryError::class.java) { - initForTest { - it.dsn = dsn - it.addIntegration(failing) - } - } - } - @Test fun `overrides envelope cache if it's not set`() { var sentryOptions: SentryOptions? = null diff --git a/sentry/src/test/java/io/sentry/util/LoadClassTest.kt b/sentry/src/test/java/io/sentry/util/LoadClassTest.kt index 901b018a86e..f73c6edd16d 100644 --- a/sentry/src/test/java/io/sentry/util/LoadClassTest.kt +++ b/sentry/src/test/java/io/sentry/util/LoadClassTest.kt @@ -74,17 +74,6 @@ class LoadClassTest { assertTrue(LoadClassInitFlag.initialized) } - - @Test - fun `loadClass returns null when the static initializer of the class throws`() { - assertNull(LoadClass().loadClass(LoadClassFailingInitProbe::class.java.name, null)) - } -} - -private object LoadClassFailingInitProbe { - init { - throw IllegalStateException("init") - } } private object IsClassAvailableNoInitFlag { From c7ca5d80ad6c803356471a7092390e80c081bab8 Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Wed, 18 Nov 2026 18:35:21 +0100 Subject: [PATCH 4/5] changelog: Move the entry to #6665 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 - 1 file changed, 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d34350ee63..be7899e2dd6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -102,7 +102,6 @@ - Nav3: Stop attributing errors and spans from an Activity or ViewPager2 page without a `SentryNavEffect` to the most recently visited Nav3 root ([#6483](https://github.com/getsentry/sentry-java/pull/6483)) - Android: Count deep sleep in breadcrumb, screenshot and view hierarchy debounce windows, so the first low-memory or battery breadcrumb after a long Doze is no longer dropped ([#6590](https://github.com/getsentry/sentry-java/pull/6590)) - Avoid duplicate serialization debug logs when calculating serialized object sizes ([#6255](https://github.com/getsentry/sentry-java/pull/6255)) -- Stop swallowing fatal errors such as `OutOfMemoryError` in the SDK code that loads native libraries and optional dependencies ([#6666](https://github.com/getsentry/sentry-java/pull/6666)) ### Dependencies From c04557958c7564c491a036b7fbd701ed335e5fad Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Thu, 19 Nov 2026 09:49:20 +0100 Subject: [PATCH 5/5] fix: Handle LinkageError at callback and optional-module call sites User and hybrid callbacks, the logback encoder, and the Apollo, Servlet and Spring calls in the integrations can throw a LinkageError that isn't fatal there, because an optional module is missing or has an incompatible version. These sites now treat it like any other exception and call ExceptionUtils.rethrowIfFatal for the rest. The options configuration in Sentry.init and SentryAndroid.init continues with the options applied so far. Scopes.close logs a LinkageError from a replaceable component and goes on with the remaining shutdown steps, while fatal errors propagate. AppState catches failures of the first ON_START dispatch again, so a throwing app state listener can't crash the main looper. The callback Javadoc moves here with the sites it describes. Refs #5513 Refs JAVA-552 Co-Authored-By: Claude Opus 5.5 --- .../java/io/sentry/android/core/AppState.java | 8 ++ .../io/sentry/android/core/SentryAndroid.java | 25 +++- .../android/replay/ReplayIntegration.kt | 15 +++ .../apollo3/SentryApollo3HttpInterceptor.kt | 80 +++++++++--- .../apollo4/SentryApollo4HttpInterceptor.kt | 80 +++++++++--- .../io/sentry/logback/SentryAppender.java | 19 ++- .../sentry/spring7/SentryRequestResolver.java | 7 + .../sentry/spring7/checkin/SentryCheckIn.java | 5 + .../spring7/checkin/SentryCheckInAdvice.java | 7 + .../spring/jakarta/SentryRequestResolver.java | 7 + .../spring/jakarta/checkin/SentryCheckIn.java | 5 + .../jakarta/checkin/SentryCheckInAdvice.java | 7 + .../sentry/spring/SentryRequestResolver.java | 7 + .../sentry/spring/checkin/SentryCheckIn.java | 5 + .../spring/checkin/SentryCheckInAdvice.java | 7 + .../main/java/io/sentry/EventProcessor.java | 5 + sentry/src/main/java/io/sentry/IScopes.java | 22 ++++ .../src/main/java/io/sentry/Integration.java | 7 + sentry/src/main/java/io/sentry/Scope.java | 5 + .../main/java/io/sentry/ScopeCallback.java | 11 ++ sentry/src/main/java/io/sentry/Scopes.java | 122 ++++++++++++++---- sentry/src/main/java/io/sentry/Sentry.java | 39 ++++++ .../src/main/java/io/sentry/SentryClient.java | 40 ++++++ .../main/java/io/sentry/SentryOptions.java | 50 +++++++ .../java/io/sentry/SentryReplayOptions.java | 10 ++ .../main/java/io/sentry/TracesSampler.java | 11 ++ .../clientreport/ClientReportRecorder.java | 7 + .../sentry/util/EventSizeLimitingUtils.java | 6 + 28 files changed, 550 insertions(+), 69 deletions(-) diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AppState.java b/sentry-android-core/src/main/java/io/sentry/android/core/AppState.java index 85ed5f78ff0..cc06670d5d9 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AppState.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AppState.java @@ -11,6 +11,7 @@ import io.sentry.SentryOptions; import io.sentry.android.core.internal.util.AndroidThreadChecker; import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.util.ExceptionUtils; import java.io.Closeable; import java.io.IOException; import java.util.List; @@ -134,6 +135,13 @@ private void addObserverInternal(final @NotNull ILogger logger) { SentryLevel.ERROR, "AppState failed to get Lifecycle and could not install lifecycle observer.", e); + } catch (Throwable t) { + // addObserver dispatches ON_START synchronously to the app state listeners that are already + // registered, such as session tracking and the scope observers of hybrid SDKs, so we can't + // know what it throws. Posted from a background init, nothing else would catch it on the + // main looper. The listeners miss this ON_START. + ExceptionUtils.rethrowIfFatal(t); + logger.log(SentryLevel.ERROR, "AppState failed to notify the app state listeners.", t); } } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java index bffbf75b980..c629d53494b 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java @@ -20,6 +20,7 @@ import io.sentry.android.fragment.FragmentLifecycleIntegration; import io.sentry.android.timber.SentryTimberIntegration; import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.util.ExceptionUtils; import io.sentry.util.LoadClass; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; @@ -79,6 +80,11 @@ public static void init(@NotNull final Context context, @NotNull ILogger logger) /** * Sentry initialization with a configuration handler that may override the default options * + *

If the configuration handler throws, init continues with the options it set before it + * failed. Fatal errors such as {@link OutOfMemoryError} are rethrown instead. The failure is only + * logged at ERROR level through the SDK logger, which prints only when debug is enabled, e.g. + * through the {@code io.sentry.debug} manifest entry. + * * @param context Application. context * @param configuration Sentry.OptionsConfiguration configuration handler */ @@ -91,6 +97,11 @@ public static void init( /** * Sentry initialization with a configuration handler and custom logger * + *

If the configuration handler throws, init continues with the options it set before it + * failed. Fatal errors such as {@link OutOfMemoryError} are rethrown instead. The failure is only + * logged at ERROR level through the SDK logger, which prints only when debug is enabled, e.g. + * through the {@code io.sentry.debug} manifest entry. + * * @param context Application. context * @param logger your custom logger that implements ILogger * @param configuration Sentry.OptionsConfiguration configuration handler @@ -150,8 +161,20 @@ public static void init( try { configuration.configure(options); + } catch (LinkageError e) { + // The callback can touch options of optional modules that are missing or have an + // incompatible version, e.g. session replay's masking options. Init continues with + // the options set before it failed. + options + .getLogger() + .log( + SentryLevel.ERROR, + "Error in the 'OptionsConfiguration.configure' callback.", + e); } catch (Throwable t) { - // let it slip, but log it + // The callback is the app's or a hybrid SDK's own code, so we can't know what it + // throws. Init continues with the options set before it failed. + ExceptionUtils.rethrowIfFatal(t); options .getLogger() .log( diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt index 6bdca6f748f..772775b32d2 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt @@ -51,6 +51,7 @@ import io.sentry.protocol.SentryId import io.sentry.transport.ICurrentDateProvider import io.sentry.transport.RateLimiter import io.sentry.transport.RateLimiter.IRateLimitObserver +import io.sentry.util.ExceptionUtils import io.sentry.util.FileUtils import io.sentry.util.HintUtils import io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion @@ -486,7 +487,14 @@ public class ReplayIntegration( val hint = Hint() hint.set(TypeCheckHint.REPLAY_FRAME_BITMAP, copy) observer.onMaskedFrameCaptured(hint, frameTimeStamp, screen) + } catch (e: LinkageError) { + // the observer needs a class that is missing or has an incompatible version + options.logger.log(ERROR, "Error in ReplayFrameObserver", e) + copy.recycle() } catch (e: Throwable) { + // The observer is the app's own code, so we can't know what it throws. The copy is + // recycled and the frame is still recorded. + ExceptionUtils.rethrowIfFatal(e) options.logger.log(ERROR, "Error in ReplayFrameObserver", e) copy.recycle() } @@ -509,7 +517,14 @@ public class ReplayIntegration( val hint = Hint() hint.set(TypeCheckHint.REPLAY_FRAME_BITMAP, bitmap) observer.onMaskedFrameCaptured(hint, frameTimestamp, screen) + } catch (e: LinkageError) { + // the observer needs a class that is missing or has an incompatible version + options.logger.log(ERROR, "Error in ReplayFrameObserver", e) + bitmap.recycle() } catch (e: Throwable) { + // The observer is the app's own code, so we can't know what it throws. The bitmap is + // recycled and the frame is still recorded. + ExceptionUtils.rethrowIfFatal(e) options.logger.log(ERROR, "Error in ReplayFrameObserver", e) bitmap.recycle() } diff --git a/sentry-apollo-3/src/main/java/io/sentry/apollo3/SentryApollo3HttpInterceptor.kt b/sentry-apollo-3/src/main/java/io/sentry/apollo3/SentryApollo3HttpInterceptor.kt index 400643cef4a..39d329d384e 100644 --- a/sentry-apollo-3/src/main/java/io/sentry/apollo3/SentryApollo3HttpInterceptor.kt +++ b/sentry-apollo-3/src/main/java/io/sentry/apollo3/SentryApollo3HttpInterceptor.kt @@ -30,6 +30,7 @@ import io.sentry.protocol.Mechanism import io.sentry.protocol.Request import io.sentry.protocol.Response import io.sentry.util.CookieUtils +import io.sentry.util.ExceptionUtils import io.sentry.util.GraphqlUtils import io.sentry.util.HttpUtils import io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion @@ -221,27 +222,7 @@ constructor( span.setData(SpanDataConvention.HTTP_RESPONSE_CONTENT_LENGTH_KEY, it) } if (beforeSpan != null) { - val wasSampled = span.isSampled == true - try { - val result = beforeSpan.execute(span, request, response) - if (result == null) { - // Span is dropped - span.spanContext.sampled = false - } - } catch (e: Throwable) { - span.spanContext.sampled = false - if (wasSampled) { - scopes.options.clientReportRecorder.recordLostEvent( - DiscardReason.CALLBACK_ERROR, - DataCategory.Span, - ) - } - scopes.options.logger.log( - SentryLevel.ERROR, - "An error occurred while executing beforeSpan on ApolloInterceptor", - e, - ) - } + executeBeforeSpan(beforeSpan, span, request, response) } span.finish() } @@ -273,6 +254,46 @@ constructor( scopes.addBreadcrumb(breadcrumb, hint) } + private fun executeBeforeSpan( + callback: BeforeSpanCallback, + span: ISpan, + request: HttpRequest, + response: HttpResponse?, + ) { + val wasSampled = span.isSampled == true + val failure = + try { + val result = callback.execute(span, request, response) + if (result == null) { + // Span is dropped + span.spanContext.sampled = false + } + null + } catch (e: LinkageError) { + // the callback needs a class that is missing or has an incompatible version + e + } catch (e: Throwable) { + // beforeSpan is the user's callback, so we can't know what it throws. The span is + // dropped, as if the callback had returned null. + ExceptionUtils.rethrowIfFatal(e) + e + } + if (failure != null) { + span.spanContext.sampled = false + if (wasSampled) { + scopes.options.clientReportRecorder.recordLostEvent( + DiscardReason.CALLBACK_ERROR, + DataCategory.Span, + ) + } + scopes.options.logger.log( + SentryLevel.ERROR, + "An error occurred while executing beforeSpan on ApolloInterceptor", + failure, + ) + } + } + // Extensions private fun Long?.ifHasValidLength(fn: (Long) -> Unit) { @@ -433,7 +454,14 @@ constructor( try { it.writeTo(buffer) data = GraphqlUtils.filterRequestBody(buffer.readUtf8(), scopes.options) + } catch (e: LinkageError) { + // Apollo has a version that doesn't match. The event is sent without the request + // body. + scopes.options.logger.log(SentryLevel.ERROR, "Error reading the request body.", e) } catch (e: Throwable) { + // writeTo runs the app's own request body code, so we can't know what it throws. + // The event is sent without the request body. + ExceptionUtils.rethrowIfFatal(e) scopes.options.logger.log(SentryLevel.ERROR, "Error reading the request body.", e) // continue because the response body alone can already give some insights } finally { @@ -465,7 +493,13 @@ constructor( event.fingerprints = fingerprints scopes.captureEvent(event, hint) + } catch (e: LinkageError) { + // Apollo has a version that doesn't match. The failed-request event is not sent. + scopes.options.logger.log(SentryLevel.ERROR, "Error capturing the GraphQL error.", e) } catch (e: Throwable) { + // This runs inside the app's GraphQL request, which must not fail because reporting it + // failed. The failed-request event is not sent. + ExceptionUtils.rethrowIfFatal(e) scopes.options.logger.log(SentryLevel.ERROR, "Error capturing the GraphQL error.", e) } } @@ -475,6 +509,10 @@ constructor( /** * Mutates span before being added. * + * If this throws, the span is dropped, as if this had returned null. Fatal errors such as + * [OutOfMemoryError] are rethrown instead. The failure is only logged at ERROR level through + * [io.sentry.SentryOptions.getLogger], which by default prints only when debug is enabled. + * * @param span the span to mutate or drop * @param request the Apollo request object * @param response the Apollo response object diff --git a/sentry-apollo-4/src/main/java/io/sentry/apollo4/SentryApollo4HttpInterceptor.kt b/sentry-apollo-4/src/main/java/io/sentry/apollo4/SentryApollo4HttpInterceptor.kt index 539bdb25b21..2cf0afa3207 100644 --- a/sentry-apollo-4/src/main/java/io/sentry/apollo4/SentryApollo4HttpInterceptor.kt +++ b/sentry-apollo-4/src/main/java/io/sentry/apollo4/SentryApollo4HttpInterceptor.kt @@ -28,6 +28,7 @@ import io.sentry.protocol.Mechanism import io.sentry.protocol.Request import io.sentry.protocol.Response import io.sentry.util.CookieUtils +import io.sentry.util.ExceptionUtils import io.sentry.util.GraphqlUtils import io.sentry.util.HttpUtils import io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion @@ -220,27 +221,7 @@ constructor( span.setData(SpanDataConvention.HTTP_RESPONSE_CONTENT_LENGTH_KEY, it) } if (beforeSpan != null) { - val wasSampled = span.isSampled == true - try { - val result = beforeSpan.execute(span, request, response) - if (result == null) { - // Span is dropped - span.spanContext.sampled = false - } - } catch (e: Throwable) { - span.spanContext.sampled = false - if (wasSampled) { - scopes.options.clientReportRecorder.recordLostEvent( - DiscardReason.CALLBACK_ERROR, - DataCategory.Span, - ) - } - scopes.options.logger.log( - SentryLevel.ERROR, - "An error occurred while executing beforeSpan in ApolloInterceptor", - e, - ) - } + executeBeforeSpan(beforeSpan, span, request, response) } span.finish() } @@ -272,6 +253,46 @@ constructor( scopes.addBreadcrumb(breadcrumb, hint) } + private fun executeBeforeSpan( + callback: BeforeSpanCallback, + span: ISpan, + request: HttpRequest, + response: HttpResponse?, + ) { + val wasSampled = span.isSampled == true + val failure = + try { + val result = callback.execute(span, request, response) + if (result == null) { + // Span is dropped + span.spanContext.sampled = false + } + null + } catch (e: LinkageError) { + // the callback needs a class that is missing or has an incompatible version + e + } catch (e: Throwable) { + // beforeSpan is the user's callback, so we can't know what it throws. The span is + // dropped, as if the callback had returned null. + ExceptionUtils.rethrowIfFatal(e) + e + } + if (failure != null) { + span.spanContext.sampled = false + if (wasSampled) { + scopes.options.clientReportRecorder.recordLostEvent( + DiscardReason.CALLBACK_ERROR, + DataCategory.Span, + ) + } + scopes.options.logger.log( + SentryLevel.ERROR, + "An error occurred while executing beforeSpan in ApolloInterceptor", + failure, + ) + } + } + // Extensions private fun Long?.ifHasValidLength(fn: (Long) -> Unit) { @@ -432,7 +453,14 @@ constructor( try { it.writeTo(buffer) data = GraphqlUtils.filterRequestBody(buffer.readUtf8(), scopes.options) + } catch (e: LinkageError) { + // Apollo has a version that doesn't match. The event is sent without the request + // body. + scopes.options.logger.log(SentryLevel.ERROR, "Error reading the request body.", e) } catch (e: Throwable) { + // writeTo runs the app's own request body code, so we can't know what it throws. + // The event is sent without the request body. + ExceptionUtils.rethrowIfFatal(e) scopes.options.logger.log(SentryLevel.ERROR, "Error reading the request body.", e) // continue because the response body alone can already give some insights } finally { @@ -464,7 +492,13 @@ constructor( event.fingerprints = fingerprints scopes.captureEvent(event, hint) + } catch (e: LinkageError) { + // Apollo has a version that doesn't match. The failed-request event is not sent. + scopes.options.logger.log(SentryLevel.ERROR, "Error capturing the GraphQL error.", e) } catch (e: Throwable) { + // This runs inside the app's GraphQL request, which must not fail because reporting it + // failed. The failed-request event is not sent. + ExceptionUtils.rethrowIfFatal(e) scopes.options.logger.log(SentryLevel.ERROR, "Error capturing the GraphQL error.", e) } } @@ -474,6 +508,10 @@ constructor( /** * Mutates span before being added. * + * If this throws, the span is dropped, as if this had returned null. Fatal errors such as + * [OutOfMemoryError] are rethrown instead. The failure is only logged at ERROR level through + * [io.sentry.SentryOptions.getLogger], which by default prints only when debug is enabled. + * * @param span the span to mutate or drop * @param request the Apollo request object * @param response the Apollo response object diff --git a/sentry-logback/src/main/java/io/sentry/logback/SentryAppender.java b/sentry-logback/src/main/java/io/sentry/logback/SentryAppender.java index 127ca7aa707..b2421b361a1 100644 --- a/sentry-logback/src/main/java/io/sentry/logback/SentryAppender.java +++ b/sentry-logback/src/main/java/io/sentry/logback/SentryAppender.java @@ -29,6 +29,7 @@ import io.sentry.protocol.Message; import io.sentry.protocol.SdkVersion; import io.sentry.util.CollectionUtils; +import io.sentry.util.ExceptionUtils; import io.sentry.util.LoggerPropertiesUtil; import java.nio.charset.StandardCharsets; import java.util.Arrays; @@ -213,8 +214,12 @@ private String formatted(@NotNull ILoggingEvent loggingEvent) { try { return new String(encoder.encode(loggingEvent), StandardCharsets.UTF_8); } catch (final Throwable t) { - // catch exceptions from possibly incorrectly configured encoder - // and fallback to default formatted message + // The encoder is the app's own, possibly misconfigured, so we can't know what it throws. A + // LinkageError from it is treated like any other exception. The event falls back to the + // default formatted message. + if (!(t instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(t); + } addWarn("Failed to encode logging event", t); } } @@ -347,6 +352,16 @@ void setTransportFactory(final @Nullable ITransportFactory transportFactory) { this.transportFactory = transportFactory; } + /** + * Sets the encoder that formats the message sent to Sentry. + * + *

If the encoder throws, the logging event's formatted message is sent instead. Fatal errors + * such as {@link OutOfMemoryError} are rethrown. The failure is reported as a warning to + * logback's status manager, which you can see with {@code } or a + * status listener. + * + * @param encoder the encoder + */ public void setEncoder(Encoder encoder) { this.encoder = encoder; } diff --git a/sentry-spring-7/src/main/java/io/sentry/spring7/SentryRequestResolver.java b/sentry-spring-7/src/main/java/io/sentry/spring7/SentryRequestResolver.java index 4995d4bfe09..24cc68896e3 100644 --- a/sentry-spring-7/src/main/java/io/sentry/spring7/SentryRequestResolver.java +++ b/sentry-spring-7/src/main/java/io/sentry/spring7/SentryRequestResolver.java @@ -7,6 +7,7 @@ import io.sentry.protocol.Request; import io.sentry.util.AutoClosableReentrantLock; import io.sentry.util.CookieUtils; +import io.sentry.util.ExceptionUtils; import io.sentry.util.HttpUtils; import io.sentry.util.Objects; import io.sentry.util.UrlUtils; @@ -116,6 +117,12 @@ private List extractSecurityCookieNames(final @NotNull HttpServletReques } } } catch (Throwable t) { + // The request and its servlet context are the container's, whose implementations differ, so + // we can't know what they throw. A LinkageError, e.g. from a Servlet API version that doesn't + // match, is handled the same way. Only the default session cookie names are filtered then. + if (!(t instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(t); + } scopes .getOptions() .getLogger() diff --git a/sentry-spring-7/src/main/java/io/sentry/spring7/checkin/SentryCheckIn.java b/sentry-spring-7/src/main/java/io/sentry/spring7/checkin/SentryCheckIn.java index ac17f85a985..663c3316650 100644 --- a/sentry-spring-7/src/main/java/io/sentry/spring7/checkin/SentryCheckIn.java +++ b/sentry-spring-7/src/main/java/io/sentry/spring7/checkin/SentryCheckIn.java @@ -42,6 +42,11 @@ /** * Monitor slug. If not set, no check-in will be sent. * + *

Placeholders and SpEL expressions in the slug are resolved. If resolving fails, the + * unresolved slug is used, so check-ins go to a monitor that likely does not exist. The failure + * is only logged as a warning through {@link io.sentry.SentryOptions#getLogger()}, which by + * default prints only when debug is enabled. + * * @return monitor slug */ @AliasFor("monitorSlug") diff --git a/sentry-spring-7/src/main/java/io/sentry/spring7/checkin/SentryCheckInAdvice.java b/sentry-spring-7/src/main/java/io/sentry/spring7/checkin/SentryCheckInAdvice.java index 2f83a079d0d..a715a3d9922 100644 --- a/sentry-spring-7/src/main/java/io/sentry/spring7/checkin/SentryCheckInAdvice.java +++ b/sentry-spring-7/src/main/java/io/sentry/spring7/checkin/SentryCheckInAdvice.java @@ -11,6 +11,7 @@ import io.sentry.SentryLevel; import io.sentry.protocol.SentryId; import io.sentry.time.Stopwatch; +import io.sentry.util.ExceptionUtils; import io.sentry.util.MonitorConfigUtils; import io.sentry.util.Objects; import io.sentry.util.TracingUtils; @@ -128,6 +129,12 @@ public SentryCheckInAdvice(final @NotNull IScopes scopes, final boolean monitorS try { monitorSlug = resolver.resolveStringValue(checkInAnnotation.value()); } catch (Throwable e) { + // The resolver evaluates the app's placeholders and SpEL expressions, so we can't know what + // it throws. A LinkageError, e.g. from a Spring version that doesn't match, is handled the + // same way. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } // When resolving fails, we fall back to the original string which may contain unresolved // expressions. Testing shows this can also happen if properties cannot be resolved (without // an exception being thrown). Sentry should alert the user about missed checkins in this diff --git a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/SentryRequestResolver.java b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/SentryRequestResolver.java index 9fcb30665cb..23eb58efed1 100644 --- a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/SentryRequestResolver.java +++ b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/SentryRequestResolver.java @@ -7,6 +7,7 @@ import io.sentry.protocol.Request; import io.sentry.util.AutoClosableReentrantLock; import io.sentry.util.CookieUtils; +import io.sentry.util.ExceptionUtils; import io.sentry.util.HttpUtils; import io.sentry.util.Objects; import io.sentry.util.UrlUtils; @@ -116,6 +117,12 @@ private List extractSecurityCookieNames(final @NotNull HttpServletReques } } } catch (Throwable t) { + // The request and its servlet context are the container's, whose implementations differ, so + // we can't know what they throw. A LinkageError, e.g. from a Servlet API version that doesn't + // match, is handled the same way. Only the default session cookie names are filtered then. + if (!(t instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(t); + } scopes .getOptions() .getLogger() diff --git a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/checkin/SentryCheckIn.java b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/checkin/SentryCheckIn.java index 89b04aa561a..82530a993a9 100644 --- a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/checkin/SentryCheckIn.java +++ b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/checkin/SentryCheckIn.java @@ -42,6 +42,11 @@ /** * Monitor slug. If not set, no check-in will be sent. * + *

Placeholders and SpEL expressions in the slug are resolved. If resolving fails, the + * unresolved slug is used, so check-ins go to a monitor that likely does not exist. The failure + * is only logged as a warning through {@link io.sentry.SentryOptions#getLogger()}, which by + * default prints only when debug is enabled. + * * @return monitor slug */ @AliasFor("monitorSlug") diff --git a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/checkin/SentryCheckInAdvice.java b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/checkin/SentryCheckInAdvice.java index a544c401966..905b311c691 100644 --- a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/checkin/SentryCheckInAdvice.java +++ b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/checkin/SentryCheckInAdvice.java @@ -11,6 +11,7 @@ import io.sentry.SentryLevel; import io.sentry.protocol.SentryId; import io.sentry.time.Stopwatch; +import io.sentry.util.ExceptionUtils; import io.sentry.util.MonitorConfigUtils; import io.sentry.util.Objects; import io.sentry.util.TracingUtils; @@ -125,6 +126,12 @@ public Object invoke(final @NotNull MethodInvocation invocation) throws Throwabl try { monitorSlug = resolver.resolveStringValue(checkInAnnotation.value()); } catch (Throwable e) { + // The resolver evaluates the app's placeholders and SpEL expressions, so we can't know what + // it throws. A LinkageError, e.g. from a Spring version that doesn't match, is handled the + // same way. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } // When resolving fails, we fall back to the original string which may contain unresolved // expressions. Testing shows this can also happen if properties cannot be resolved (without // an exception being thrown). Sentry should alert the user about missed checkins in this diff --git a/sentry-spring/src/main/java/io/sentry/spring/SentryRequestResolver.java b/sentry-spring/src/main/java/io/sentry/spring/SentryRequestResolver.java index 1c8ec52ac88..144931e3bb4 100644 --- a/sentry-spring/src/main/java/io/sentry/spring/SentryRequestResolver.java +++ b/sentry-spring/src/main/java/io/sentry/spring/SentryRequestResolver.java @@ -7,6 +7,7 @@ import io.sentry.protocol.Request; import io.sentry.util.AutoClosableReentrantLock; import io.sentry.util.CookieUtils; +import io.sentry.util.ExceptionUtils; import io.sentry.util.HttpUtils; import io.sentry.util.Objects; import io.sentry.util.UrlUtils; @@ -116,6 +117,12 @@ private List extractSecurityCookieNames(final @NotNull HttpServletReques } } } catch (Throwable t) { + // The request and its servlet context are the container's, whose implementations differ, so + // we can't know what they throw. A LinkageError, e.g. from a Servlet API version that doesn't + // match, is handled the same way. Only the default session cookie names are filtered then. + if (!(t instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(t); + } scopes .getOptions() .getLogger() diff --git a/sentry-spring/src/main/java/io/sentry/spring/checkin/SentryCheckIn.java b/sentry-spring/src/main/java/io/sentry/spring/checkin/SentryCheckIn.java index 55fedd93c2e..2c10ae38a76 100644 --- a/sentry-spring/src/main/java/io/sentry/spring/checkin/SentryCheckIn.java +++ b/sentry-spring/src/main/java/io/sentry/spring/checkin/SentryCheckIn.java @@ -42,6 +42,11 @@ /** * Monitor slug. If not set, no check-in will be sent. * + *

Placeholders and SpEL expressions in the slug are resolved. If resolving fails, the + * unresolved slug is used, so check-ins go to a monitor that likely does not exist. The failure + * is only logged as a warning through {@link io.sentry.SentryOptions#getLogger()}, which by + * default prints only when debug is enabled. + * * @return monitor slug */ @AliasFor("monitorSlug") diff --git a/sentry-spring/src/main/java/io/sentry/spring/checkin/SentryCheckInAdvice.java b/sentry-spring/src/main/java/io/sentry/spring/checkin/SentryCheckInAdvice.java index f6923c77e6e..e971dd0b7d2 100644 --- a/sentry-spring/src/main/java/io/sentry/spring/checkin/SentryCheckInAdvice.java +++ b/sentry-spring/src/main/java/io/sentry/spring/checkin/SentryCheckInAdvice.java @@ -11,6 +11,7 @@ import io.sentry.SentryLevel; import io.sentry.protocol.SentryId; import io.sentry.time.Stopwatch; +import io.sentry.util.ExceptionUtils; import io.sentry.util.MonitorConfigUtils; import io.sentry.util.Objects; import io.sentry.util.TracingUtils; @@ -125,6 +126,12 @@ public Object invoke(final @NotNull MethodInvocation invocation) throws Throwabl try { monitorSlug = resolver.resolveStringValue(checkInAnnotation.value()); } catch (Throwable e) { + // The resolver evaluates the app's placeholders and SpEL expressions, so we can't know what + // it throws. A LinkageError, e.g. from a Spring version that doesn't match, is handled the + // same way. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } // When resolving fails, we fall back to the original string which may contain unresolved // expressions. // Testing shows this can also happen if properties cannot be resolved (without an exception diff --git a/sentry/src/main/java/io/sentry/EventProcessor.java b/sentry/src/main/java/io/sentry/EventProcessor.java index 928fd022095..05f600d4bd9 100644 --- a/sentry/src/main/java/io/sentry/EventProcessor.java +++ b/sentry/src/main/java/io/sentry/EventProcessor.java @@ -6,6 +6,11 @@ /** * An Event Processor that may mutate or drop an event. Runs for SentryEvent or SentryTransaction + * + *

If a processor throws, the event is dropped and the exception is logged at {@link + * SentryLevel#ERROR} through {@link SentryOptions#getLogger()}, which by default prints only when + * {@link SentryOptions#isDebug()} is enabled. Fatal errors, such as {@link OutOfMemoryError}, are + * rethrown. */ public interface EventProcessor { diff --git a/sentry/src/main/java/io/sentry/IScopes.java b/sentry/src/main/java/io/sentry/IScopes.java index 6b5a2b8a5b7..c1ffa4f7d69 100644 --- a/sentry/src/main/java/io/sentry/IScopes.java +++ b/sentry/src/main/java/io/sentry/IScopes.java @@ -351,6 +351,12 @@ default void addBreadcrumb(@NotNull String message, @NotNull String category) { * changes may be dropped when executed in parallel. Use {@link * IScopes#configureScope(ScopeCallback)} instead. * + *

If the callback throws, the rest of it is skipped and the exception is logged at {@link + * SentryLevel#ERROR} through {@link SentryOptions#getLogger()}, which by default prints only when + * {@link SentryOptions#isDebug()} is enabled. Fatal errors, such as {@link OutOfMemoryError}, are + * rethrown. Before {@link Sentry#init}, the callback runs on a no-op scope and nothing it throws + * is caught. + * * @param callback the callback */ void withScope(@NotNull ScopeCallback callback); @@ -364,6 +370,12 @@ default void addBreadcrumb(@NotNull String message, @NotNull String category) { * changes may be dropped when executed in parallel. Use {@link IScopes#configureScope(ScopeType, * ScopeCallback)} instead. * + *

If the callback throws, the rest of it is skipped and the exception is logged at {@link + * SentryLevel#ERROR} through {@link SentryOptions#getLogger()}, which by default prints only when + * {@link SentryOptions#isDebug()} is enabled. Fatal errors, such as {@link OutOfMemoryError}, are + * rethrown. Before {@link Sentry#init}, the callback runs on a no-op scope and nothing it throws + * is caught. + * * @param callback the callback */ void withIsolationScope(@NotNull ScopeCallback callback); @@ -371,6 +383,11 @@ default void addBreadcrumb(@NotNull String message, @NotNull String category) { /** * Configures the scope through the callback. * + *

If the callback throws, the rest of it is skipped and the exception is logged at {@link + * SentryLevel#ERROR} through {@link SentryOptions#getLogger()}, which by default prints only when + * {@link SentryOptions#isDebug()} is enabled. Fatal errors, such as {@link OutOfMemoryError}, are + * rethrown. Before {@link Sentry#init}, the callback isn't run. + * * @param callback The configure scope callback. */ default void configureScope(@NotNull ScopeCallback callback) { @@ -380,6 +397,11 @@ default void configureScope(@NotNull ScopeCallback callback) { /** * Configures the scope through the callback. * + *

If the callback throws, the rest of it is skipped and the exception is logged at {@link + * SentryLevel#ERROR} through {@link SentryOptions#getLogger()}, which by default prints only when + * {@link SentryOptions#isDebug()} is enabled. Fatal errors, such as {@link OutOfMemoryError}, are + * rethrown. Before {@link Sentry#init}, the callback isn't run. + * * @param callback The configure scope callback. */ void configureScope(@Nullable ScopeType scopeType, @NotNull ScopeCallback callback); diff --git a/sentry/src/main/java/io/sentry/Integration.java b/sentry/src/main/java/io/sentry/Integration.java index 1b1a520473e..6ee16b2d356 100644 --- a/sentry/src/main/java/io/sentry/Integration.java +++ b/sentry/src/main/java/io/sentry/Integration.java @@ -10,6 +10,13 @@ public interface Integration { /** * Registers an integration * + *

If this method throws, {@link Sentry#init} skips the integration and continues with the next + * one, so the SDK starts without what this integration would have set up. Fatal errors such as + * {@link OutOfMemoryError} are rethrown instead. The skipped integration is only reported as a + * warning through {@link SentryOptions#getLogger()}, which by default prints only when {@link + * SentryOptions#isDebug()} is enabled. To find out whether your integration registered, enable + * debug and look for "Failed to register the integration" in the log. + * * @param scopes the Scopes * @param options the options */ diff --git a/sentry/src/main/java/io/sentry/Scope.java b/sentry/src/main/java/io/sentry/Scope.java index b05e4d9d05c..c58c6cd773e 100644 --- a/sentry/src/main/java/io/sentry/Scope.java +++ b/sentry/src/main/java/io/sentry/Scope.java @@ -496,6 +496,11 @@ public Queue getBreadcrumbs() { try (final @NotNull ISentryLifecycleToken ignored = SentryCallbackReentrancyGuard.enter()) { return callback.execute(breadcrumb, hint); } catch (Throwable e) { + // A user callback, so we can't know what it throws. A LinkageError from it is treated like + // any other exception. As the spec asks, the breadcrumb is dropped. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } options .getLogger() .log( diff --git a/sentry/src/main/java/io/sentry/ScopeCallback.java b/sentry/src/main/java/io/sentry/ScopeCallback.java index 96d15c29f77..baa0c93d286 100644 --- a/sentry/src/main/java/io/sentry/ScopeCallback.java +++ b/sentry/src/main/java/io/sentry/ScopeCallback.java @@ -3,5 +3,16 @@ import org.jetbrains.annotations.NotNull; public interface ScopeCallback { + /** + * Runs with the scope to read or change. + * + *

If this callback throws, the rest of it is skipped and the exception is logged at {@link + * SentryLevel#ERROR} through {@link SentryOptions#getLogger()}, which by default prints only when + * {@link SentryOptions#isDebug()} is enabled. When the callback was passed to a capture method, + * the event is captured with the scope as it was before the callback ran. Fatal errors, such as + * {@link OutOfMemoryError}, are rethrown. + * + * @param scope the scope + */ void run(@NotNull IScope scope); } diff --git a/sentry/src/main/java/io/sentry/Scopes.java b/sentry/src/main/java/io/sentry/Scopes.java index 927b2b6f117..ea0f8fdeae6 100644 --- a/sentry/src/main/java/io/sentry/Scopes.java +++ b/sentry/src/main/java/io/sentry/Scopes.java @@ -193,6 +193,11 @@ private void assignTraceContext(final @NotNull SentryEvent event) { callback.run(localScope); return localScope; } catch (Throwable t) { + // A user callback, so we can't know what it throws. A LinkageError from it is treated + // like any other exception. The event is captured with the unchanged scope. + if (!(t instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(t); + } getOptions() .getLogger() .log(SentryLevel.ERROR, "Error in the 'ScopeCallback' callback.", t); @@ -406,7 +411,6 @@ public void close() { } @Override - @SuppressWarnings("FutureReturnValueIgnored") public void close(final boolean isRestarting) { if (!isEnabled()) { getOptions() @@ -438,7 +442,20 @@ public void close(final boolean isRestarting) { if (eventProcessor instanceof Closeable) { try { ((Closeable) eventProcessor).close(); + } catch (LinkageError e) { + // The event processor needs an optional dependency that is missing or has an + // incompatible version. The remaining event processors are still closed. + getOptions() + .getLogger() + .log( + SentryLevel.WARNING, + "Failed to close the event processor {}.", + eventProcessor, + e); } catch (Throwable e) { + // Event processors can be user-provided, so we can't know what they throw. The + // remaining event processors are still closed. + ExceptionUtils.rethrowIfFatal(e); getOptions() .getLogger() .log( @@ -452,34 +469,26 @@ public void close(final boolean isRestarting) { configureScope(scope -> scope.clear()); configureScope(ScopeType.ISOLATION, scope -> scope.clear()); - getOptions().getBackpressureMonitor().close(); - getOptions().getTransactionProfiler().close(); - getOptions().getContinuousProfiler().close(true); - getOptions().getCompositePerformanceCollector().close(); - getOptions().getConnectionStatusProvider().close(); + closeComponent("backpressure monitor", () -> getOptions().getBackpressureMonitor().close()); + closeComponent("transaction profiler", () -> getOptions().getTransactionProfiler().close()); + closeComponent( + "continuous profiler", () -> getOptions().getContinuousProfiler().close(true)); + closeComponent( + "performance collector", () -> getOptions().getCompositePerformanceCollector().close()); + closeComponent( + "connection status provider", () -> getOptions().getConnectionStatusProvider().close()); // On restart we intentionally leave the timer executor running so that pending idle/ // deadline timeouts of transactions started before the restart still fire and finish // those transactions. It self-terminates once idle (allowCoreThreadTimeOut). if (!isRestarting) { - getOptions().getTimerExecutorService().close(getOptions().getShutdownTimeoutMillis()); - } - final @NotNull ISentryExecutorService executorService = getOptions().getExecutorService(); - if (isRestarting) { - try { - executorService.submit( - () -> executorService.close(getOptions().getShutdownTimeoutMillis())); - } catch (RejectedExecutionException e) { - getOptions() - .getLogger() - .log( - SentryLevel.WARNING, - "Failed to submit executor service shutdown task during restart. Shutting down synchronously.", - e); - executorService.close(getOptions().getShutdownTimeoutMillis()); - } - } else { - executorService.close(getOptions().getShutdownTimeoutMillis()); + closeComponent( + "timer executor service", + () -> + getOptions() + .getTimerExecutorService() + .close(getOptions().getShutdownTimeoutMillis())); } + closeComponent("executor service", () -> closeExecutorService(isRestarting)); // TODO: should we end session before closing client? configureScope(ScopeType.CURRENT, scope -> scope.getClient().close(isRestarting)); @@ -494,6 +503,46 @@ public void close(final boolean isRestarting) { } } + private interface ShutdownStep { + void run() throws Exception; + } + + /** + * Integrations and the app can replace these components, so one may need an optional dependency + * that is missing or has an incompatible version. Its LinkageError is logged and the remaining + * shutdown steps still run, which matters on re-init, where {@link Sentry#init} calls {@link + * #close(boolean)}. + */ + private void closeComponent(final @NotNull String component, final @NotNull ShutdownStep step) + throws Exception { + try { + step.run(); + } catch (LinkageError e) { + getOptions().getLogger().log(SentryLevel.ERROR, e, "Failed to close the %s.", component); + } + } + + @SuppressWarnings("FutureReturnValueIgnored") + private void closeExecutorService(final boolean isRestarting) { + final @NotNull ISentryExecutorService executorService = getOptions().getExecutorService(); + if (isRestarting) { + try { + executorService.submit( + () -> executorService.close(getOptions().getShutdownTimeoutMillis())); + } catch (RejectedExecutionException e) { + getOptions() + .getLogger() + .log( + SentryLevel.WARNING, + "Failed to submit executor service shutdown task during restart. Shutting down synchronously.", + e); + executorService.close(getOptions().getShutdownTimeoutMillis()); + } + } else { + executorService.close(getOptions().getShutdownTimeoutMillis()); + } + } + @Override public void addBreadcrumb(final @NotNull Breadcrumb breadcrumb, final @Nullable Hint hint) { if (!isEnabled()) { @@ -683,6 +732,11 @@ public void withScope(final @NotNull ScopeCallback callback) { try { callback.run(NoOpScope.getInstance()); } catch (Throwable e) { + // A user callback, so we can't know what it throws. A LinkageError from it is treated + // like any other exception. The rest of the callback is skipped. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } getOptions().getLogger().log(SentryLevel.ERROR, "Error in the 'withScope' callback.", e); } @@ -691,6 +745,11 @@ public void withScope(final @NotNull ScopeCallback callback) { try (final @NotNull ISentryLifecycleToken ignored = forkedScopes.makeCurrent()) { callback.run(forkedScopes.getScope()); } catch (Throwable e) { + // A user callback, so we can't know what it throws. A LinkageError from it is treated + // like any other exception. The rest of the callback is skipped. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } getOptions().getLogger().log(SentryLevel.ERROR, "Error in the 'withScope' callback.", e); } } @@ -702,6 +761,11 @@ public void withIsolationScope(final @NotNull ScopeCallback callback) { try { callback.run(NoOpScope.getInstance()); } catch (Throwable e) { + // A user callback, so we can't know what it throws. A LinkageError from it is treated + // like any other exception. The rest of the callback is skipped. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } getOptions() .getLogger() .log(SentryLevel.ERROR, "Error in the 'withIsolationScope' callback.", e); @@ -712,6 +776,11 @@ public void withIsolationScope(final @NotNull ScopeCallback callback) { try (final @NotNull ISentryLifecycleToken ignored = forkedScopes.makeCurrent()) { callback.run(forkedScopes.getIsolationScope()); } catch (Throwable e) { + // A user callback, so we can't know what it throws. A LinkageError from it is treated + // like any other exception. The rest of the callback is skipped. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } getOptions() .getLogger() .log(SentryLevel.ERROR, "Error in the 'withIsolationScope' callback.", e); @@ -732,6 +801,11 @@ public void configureScope( try { callback.run(combinedScope.getSpecificScope(scopeType)); } catch (Throwable e) { + // A user callback, so we can't know what it throws. A LinkageError from it is treated + // like any other exception. The rest of the callback is skipped. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } getOptions() .getLogger() .log(SentryLevel.ERROR, "Error in the 'configureScope' callback.", e); diff --git a/sentry/src/main/java/io/sentry/Sentry.java b/sentry/src/main/java/io/sentry/Sentry.java index 7f7879864e5..213a57e0de8 100644 --- a/sentry/src/main/java/io/sentry/Sentry.java +++ b/sentry/src/main/java/io/sentry/Sentry.java @@ -253,7 +253,18 @@ private static void applyOptionsConfiguration( OptionsConfiguration optionsConfiguration, T options) { try { optionsConfiguration.configure(options); + } catch (LinkageError e) { + // On Android, the callback also runs the SDK's own options setup, which constructs + // integrations from optional modules that may be missing or have an incompatible version. + // The SDK is initialized with the options applied before it failed. + options + .getLogger() + .log(SentryLevel.ERROR, "Error in the 'OptionsConfiguration.configure' callback.", e); } catch (Throwable t) { + // The callback is the app's own code, and on Android also the SDK's options setup, so we + // can't know what it throws. The SDK is initialized with the options applied before it + // failed. + ExceptionUtils.rethrowIfFatal(t); options .getLogger() .log(SentryLevel.ERROR, "Error in the 'OptionsConfiguration.configure' callback.", t); @@ -1047,6 +1058,12 @@ public static void removeExtra(final @Nullable String key) { *

Unlike {@link Sentry#pushScope()} this also forks in global hub mode, since the previous * scopes are always restored once the callback returns. * + *

If the callback throws, the rest of it is skipped and the exception is logged at {@link + * SentryLevel#ERROR} through {@link SentryOptions#getLogger()}, which by default prints only when + * {@link SentryOptions#isDebug()} is enabled. Fatal errors, such as {@link OutOfMemoryError}, are + * rethrown. Before {@link #init} and after {@link #close}, the callback runs on a no-op scope and + * nothing it throws is caught. + * * @param callback the callback */ public static void withScope(final @NotNull ScopeCallback callback) { @@ -1060,6 +1077,12 @@ public static void withScope(final @NotNull ScopeCallback callback) { *

Unlike {@link Sentry#pushIsolationScope()} this also forks in global hub mode, since the * previous scopes are always restored once the callback returns. * + *

If the callback throws, the rest of it is skipped and the exception is logged at {@link + * SentryLevel#ERROR} through {@link SentryOptions#getLogger()}, which by default prints only when + * {@link SentryOptions#isDebug()} is enabled. Fatal errors, such as {@link OutOfMemoryError}, are + * rethrown. Before {@link #init} and after {@link #close}, the callback runs on a no-op scope and + * nothing it throws is caught. + * * @param callback the callback */ public static void withIsolationScope(final @NotNull ScopeCallback callback) { @@ -1069,6 +1092,11 @@ public static void withIsolationScope(final @NotNull ScopeCallback callback) { /** * Configures the scope through the callback. * + *

If the callback throws, the rest of it is skipped and the exception is logged at {@link + * SentryLevel#ERROR} through {@link SentryOptions#getLogger()}, which by default prints only when + * {@link SentryOptions#isDebug()} is enabled. Fatal errors, such as {@link OutOfMemoryError}, are + * rethrown. Before {@link #init} and after {@link #close}, the callback isn't run. + * * @param callback The configure scope callback. */ public static void configureScope(final @NotNull ScopeCallback callback) { @@ -1078,6 +1106,11 @@ public static void configureScope(final @NotNull ScopeCallback callback) { /** * Configures the scope through the callback. * + *

If the callback throws, the rest of it is skipped and the exception is logged at {@link + * SentryLevel#ERROR} through {@link SentryOptions#getLogger()}, which by default prints only when + * {@link SentryOptions#isDebug()} is enabled. Fatal errors, such as {@link OutOfMemoryError}, are + * rethrown. Before {@link #init} and after {@link #close}, the callback isn't run. + * * @param callback The configure scope callback. */ public static void configureScope( @@ -1281,6 +1314,12 @@ public interface OptionsConfiguration { /** * configure the options * + *

If this callback throws, the SDK is initialized with the options it set before the + * exception, and the exception is logged at {@link SentryLevel#ERROR} through {@link + * SentryOptions#getLogger()}. By default that prints only when {@link SentryOptions#isDebug()} + * was enabled before the exception. Fatal errors, such as {@link OutOfMemoryError}, are + * rethrown. + * * @param options the options */ void configure(@NotNull T options); diff --git a/sentry/src/main/java/io/sentry/SentryClient.java b/sentry/src/main/java/io/sentry/SentryClient.java index ba279517584..29ac3de4d63 100644 --- a/sentry/src/main/java/io/sentry/SentryClient.java +++ b/sentry/src/main/java/io/sentry/SentryClient.java @@ -230,6 +230,11 @@ private boolean shouldApplyScopeData(final @NotNull CheckIn event, final @NotNul try (final @NotNull ISentryLifecycleToken ignored = SentryCallbackReentrancyGuard.enter()) { shouldCaptureReplay = beforeErrorSampling.execute(event, hint); } catch (Throwable e) { + // A user callback, so we can't know what it throws. A LinkageError from it is treated + // like any other exception. As the spec asks, the replay is not captured for this error. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } options .getLogger() .log( @@ -996,6 +1001,11 @@ public void captureSession(final @NotNull Session session, final @Nullable Hint try (final @NotNull ISentryLifecycleToken ignored = SentryCallbackReentrancyGuard.enter()) { beforeEnvelopeCallback.execute(envelope, hint); } catch (Throwable e) { + // A callback set by an integration or a hybrid SDK, so we can't know what it throws. A + // LinkageError from it is treated like any other exception. The envelope is still sent. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } options .getLogger() .log(SentryLevel.ERROR, "The BeforeEnvelope callback threw an exception.", e); @@ -1684,6 +1694,11 @@ private void sortBreadcrumbsByDate( try (final @NotNull ISentryLifecycleToken ignored = SentryCallbackReentrancyGuard.enter()) { event = beforeSend.execute(event, hint); } catch (Throwable e) { + // A user callback, so we can't know what it throws. A LinkageError from it is treated like + // any other exception. As the spec asks, the event is dropped. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } options .getLogger() .log( @@ -1713,6 +1728,11 @@ private void sortBreadcrumbsByDate( try (final @NotNull ISentryLifecycleToken ignored = SentryCallbackReentrancyGuard.enter()) { transaction = beforeSendTransaction.execute(transaction, hint); } catch (Throwable e) { + // A user callback, so we can't know what it throws. A LinkageError from it is treated like + // any other exception. As the spec asks, the transaction is dropped. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } options .getLogger() .log( @@ -1773,6 +1793,11 @@ private void sortBreadcrumbsByDate( try (final @NotNull ISentryLifecycleToken ignored = SentryCallbackReentrancyGuard.enter()) { event = beforeSendFeedback.execute(event, hint); } catch (Throwable e) { + // A user callback, so we can't know what it throws. A LinkageError from it is treated like + // any other exception. As the spec asks, the feedback is dropped. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } options .getLogger() .log( @@ -1800,6 +1825,11 @@ private void sortBreadcrumbsByDate( try (final @NotNull ISentryLifecycleToken ignored = SentryCallbackReentrancyGuard.enter()) { event = beforeSendReplay.execute(event, hint); } catch (Throwable e) { + // A user callback, so we can't know what it throws. A LinkageError from it is treated like + // any other exception. As the spec asks, the replay segment is dropped. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } options .getLogger() .log( @@ -1828,6 +1858,11 @@ private void sortBreadcrumbsByDate( try (final @NotNull ISentryLifecycleToken ignored = SentryCallbackReentrancyGuard.enter()) { event = beforeSendLog.execute(event); } catch (Throwable e) { + // A user callback, so we can't know what it throws. A LinkageError from it is treated like + // any other exception. As the spec asks, the log is dropped. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } options .getLogger() .log( @@ -1853,6 +1888,11 @@ private void sortBreadcrumbsByDate( try (final @NotNull ISentryLifecycleToken ignored = SentryCallbackReentrancyGuard.enter()) { event = beforeSendMetric.execute(event, hint); } catch (Throwable e) { + // A user callback, so we can't know what it throws. A LinkageError from it is treated like + // any other exception. As the spec asks, the metric is dropped. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } options .getLogger() .log( diff --git a/sentry/src/main/java/io/sentry/SentryOptions.java b/sentry/src/main/java/io/sentry/SentryOptions.java index 60b1f3cd426..df9af9103d5 100644 --- a/sentry/src/main/java/io/sentry/SentryOptions.java +++ b/sentry/src/main/java/io/sentry/SentryOptions.java @@ -3548,6 +3548,11 @@ public interface BeforeSendCallback { * integration that routes logs back into Sentry. Such nested captures are silently dropped to * prevent infinite recursion. * + *

If this callback throws, the event is dropped and the exception is logged at {@link + * SentryLevel#ERROR} through {@link SentryOptions#getLogger()}, which by default prints only + * when {@link SentryOptions#isDebug()} is enabled. Fatal errors, such as {@link + * OutOfMemoryError}, are rethrown. + * * @param event the event * @param hint the hints * @return the original event or the mutated event or null if event was dropped @@ -3566,6 +3571,11 @@ public interface BeforeSendTransactionCallback { * integration that routes logs back into Sentry. Such nested captures are silently dropped to * prevent infinite recursion. * + *

If this callback throws, the transaction is dropped and the exception is logged at {@link + * SentryLevel#ERROR} through {@link SentryOptions#getLogger()}, which by default prints only + * when {@link SentryOptions#isDebug()} is enabled. Fatal errors, such as {@link + * OutOfMemoryError}, are rethrown. + * * @param transaction the transaction * @param hint the hints * @return the original transaction or the mutated transaction or null if transaction was @@ -3587,6 +3597,11 @@ public interface BeforeSendReplayCallback { * integration that routes logs back into Sentry. Such nested captures are silently dropped to * prevent infinite recursion. * + *

If this callback throws, the replay event is dropped and the exception is logged at {@link + * SentryLevel#ERROR} through {@link SentryOptions#getLogger()}, which by default prints only + * when {@link SentryOptions#isDebug()} is enabled. Fatal errors, such as {@link + * OutOfMemoryError}, are rethrown. + * * @param event the event * @param hint the hint, contains {@link ReplayRecording}, can be accessed via {@link * Hint#getReplayRecording()} @@ -3606,6 +3621,11 @@ public interface BeforeBreadcrumbCallback { * integration that routes logs back into Sentry. Such nested captures are silently dropped to * prevent infinite recursion. * + *

If this callback throws, the breadcrumb is dropped and the exception is logged at {@link + * SentryLevel#ERROR} through {@link SentryOptions#getLogger()}, which by default prints only + * when {@link SentryOptions#isDebug()} is enabled. Fatal errors, such as {@link + * OutOfMemoryError}, are rethrown. + * * @param breadcrumb the breadcrumb * @param hint the hints, usually the source of the breadcrumb * @return the original breadcrumb or the mutated breadcrumb of null if breadcrumb was dropped @@ -3621,6 +3641,11 @@ public interface OnOversizedEventCallback { * Called when an oversized event is detected. This callback allows custom handling of oversized * events before automatic reduction steps are applied. * + *

If this callback throws, its result is ignored, the automatic reduction continues with the + * original event, and the exception is logged at {@link SentryLevel#ERROR} through {@link + * SentryOptions#getLogger()}, which by default prints only when {@link SentryOptions#isDebug()} + * is enabled. Fatal errors, such as {@link OutOfMemoryError}, are rethrown. + * * @param event the oversized event * @param hint the hints * @return the modified event (should ideally be reduced in size) @@ -3635,6 +3660,11 @@ public interface OnDiscardCallback { /** * Best-effort record of data discarded before reaching Sentry * + *

If this callback throws, the exception is logged at {@link SentryLevel#ERROR} through + * {@link SentryOptions#getLogger()}, which by default prints only when {@link + * SentryOptions#isDebug()} is enabled. Fatal errors, such as {@link OutOfMemoryError}, are + * rethrown. + * * @param reason the reason data was dropped * @param category the type of data discarded * @param number the number of discarded data items @@ -3650,6 +3680,11 @@ public interface TracesSamplerCallback { * Calculates the sampling value used to determine if transaction is going to be sent to Sentry * backend. * + *

If this callback throws, the transaction is not sampled and the exception is logged at + * {@link SentryLevel#ERROR} through {@link SentryOptions#getLogger()}, which by default prints + * only when {@link SentryOptions#isDebug()} is enabled. Fatal errors, such as {@link + * OutOfMemoryError}, are rethrown. + * * @param samplingContext the sampling context * @return sampling value or {@code null} if decision has not been taken */ @@ -3664,6 +3699,11 @@ public interface ProfilesSamplerCallback { * Calculates the sampling value used to determine if a profile is going to be sent to Sentry * backend. * + *

If this callback throws, no profile is recorded and the exception is logged at {@link + * SentryLevel#ERROR} through {@link SentryOptions#getLogger()}, which by default prints only + * when {@link SentryOptions#isDebug()} is enabled. Fatal errors, such as {@link + * OutOfMemoryError}, are rethrown. + * * @param samplingContext the sampling context * @return sampling value or {@code null} if decision has not been taken */ @@ -4229,6 +4269,11 @@ public interface BeforeSendLogCallback { * integration that routes logs back into Sentry. Such nested captures are silently dropped to * prevent infinite recursion. * + *

If this callback throws, the log is dropped and the exception is logged at {@link + * SentryLevel#ERROR} through {@link SentryOptions#getLogger()}, which by default prints only + * when {@link SentryOptions#isDebug()} is enabled. Fatal errors, such as {@link + * OutOfMemoryError}, are rethrown. + * * @param event the event * @return the original log event or the mutated event or null if event was dropped */ @@ -4286,6 +4331,11 @@ public interface BeforeSendMetricCallback { * integration that routes logs back into Sentry. Such nested captures are silently dropped to * prevent infinite recursion. * + *

If this callback throws, the metric is dropped and the exception is logged at {@link + * SentryLevel#ERROR} through {@link SentryOptions#getLogger()}, which by default prints only + * when {@link SentryOptions#isDebug()} is enabled. Fatal errors, such as {@link + * OutOfMemoryError}, are rethrown. + * * @param metric the metric * @return the original metric, mutated metric or null if metric was dropped */ diff --git a/sentry/src/main/java/io/sentry/SentryReplayOptions.java b/sentry/src/main/java/io/sentry/SentryReplayOptions.java index a068e12f2a8..137569b3a59 100644 --- a/sentry/src/main/java/io/sentry/SentryReplayOptions.java +++ b/sentry/src/main/java/io/sentry/SentryReplayOptions.java @@ -32,6 +32,11 @@ public interface BeforeErrorSamplingCallback { * integration that routes logs back into Sentry. Such nested captures are silently dropped to * prevent infinite recursion. * + *

If this callback throws, the replay is not captured for this error and the exception is + * logged at {@link SentryLevel#ERROR} through {@link SentryOptions#getLogger()}, which by + * default prints only when {@link SentryOptions#isDebug()} is enabled. Fatal errors, such as + * {@link OutOfMemoryError}, are rethrown. + * * @param event the error event that triggered the replay capture * @param hint the hint associated with the event * @return {@code true} if the error sample rate should be checked, {@code false} to skip replay @@ -56,6 +61,11 @@ public interface ReplayFrameObserver { /** * Called when a masked replay frame is captured. * + *

If this method throws, the SDK recycles the bitmap and still records the frame. The + * exception is only reported as an error through {@link SentryOptions#getLogger()}, which by + * default prints only when {@link SentryOptions#isDebug()} is enabled, so enable debug to find + * out whether your observer fails. Errors such as {@link OutOfMemoryError} are not caught. + * * @param hint contains the frame bitmap under {@link TypeCheckHint#REPLAY_FRAME_BITMAP} * @param frameTimestamp the timestamp (in milliseconds since epoch) when the frame was captured * @param screenName the current screen name, or {@code null} if unknown diff --git a/sentry/src/main/java/io/sentry/TracesSampler.java b/sentry/src/main/java/io/sentry/TracesSampler.java index bb6e5d9f11f..9f699f88bd3 100644 --- a/sentry/src/main/java/io/sentry/TracesSampler.java +++ b/sentry/src/main/java/io/sentry/TracesSampler.java @@ -1,6 +1,7 @@ package io.sentry; import io.sentry.clientreport.DiscardReason; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Objects; import io.sentry.util.SampleRateUtils; import org.jetbrains.annotations.ApiStatus; @@ -31,6 +32,11 @@ public TracesSamplingDecision sample(final @NotNull SamplingContext samplingCont try { profilesSampleRate = options.getProfilesSampler().sample(samplingContext); } catch (Throwable t) { + // A user callback, so we can't know what it throws. A LinkageError from it is treated like + // any other exception. The transaction is not profiled. + if (!(t instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(t); + } profilesSamplerFailed = true; options .getLogger() @@ -47,6 +53,11 @@ public TracesSamplingDecision sample(final @NotNull SamplingContext samplingCont try { samplerResult = options.getTracesSampler().sample(samplingContext); } catch (Throwable t) { + // A user callback, so we can't know what it throws. A LinkageError from it is treated like + // any other exception. As the spec asks, the transaction is dropped. + if (!(t instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(t); + } options .getLogger() .log(SentryLevel.ERROR, "Error in the 'TracesSamplerCallback' callback.", t); diff --git a/sentry/src/main/java/io/sentry/clientreport/ClientReportRecorder.java b/sentry/src/main/java/io/sentry/clientreport/ClientReportRecorder.java index ba6d60e2563..08c00379b4e 100644 --- a/sentry/src/main/java/io/sentry/clientreport/ClientReportRecorder.java +++ b/sentry/src/main/java/io/sentry/clientreport/ClientReportRecorder.java @@ -9,6 +9,7 @@ import io.sentry.SentryOptions; import io.sentry.protocol.SentrySpan; import io.sentry.protocol.SentryTransaction; +import io.sentry.util.ExceptionUtils; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -151,6 +152,12 @@ private void executeOnDiscard( try { options.getOnDiscard().execute(reason, category, countToAdd); } catch (Throwable e) { + // A user callback, so we can't know what it throws. A LinkageError from it is treated like + // any other exception. Only this notification is lost; the discard is still counted in the + // client report. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } options.getLogger().log(SentryLevel.ERROR, "The onDiscard callback threw an exception.", e); } } diff --git a/sentry/src/main/java/io/sentry/util/EventSizeLimitingUtils.java b/sentry/src/main/java/io/sentry/util/EventSizeLimitingUtils.java index c6c3d1a48b2..9a167294386 100644 --- a/sentry/src/main/java/io/sentry/util/EventSizeLimitingUtils.java +++ b/sentry/src/main/java/io/sentry/util/EventSizeLimitingUtils.java @@ -69,6 +69,12 @@ private EventSizeLimitingUtils() {} return reducedEvent; } } catch (Throwable e) { + // A user callback, so we can't know what it throws. A LinkageError from it is treated + // like any other exception. Its result is ignored, and the automatic reduction continues + // with the original event. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } options .getLogger() .log(