Skip to content

Commit f9a4595

Browse files
runningcodeclaude
andcommitted
fix: Narrow Throwable catches where LinkageError is expected
ExceptionUtils.rethrowIfFatal rethrows LinkageError, but at these sites a LinkageError is the expected failure: a native library that failed to load, an optional dependency that is missing, or a Compose or androidx version that doesn't match. Catch it explicitly first, and narrow the rest to the types the guarded code throws. Where the code calls app views, user integrations or JNI, keep the broad catch and call rethrowIfFatal after the LinkageError arm. Also stop QueueFile from deleting its file on an OutOfMemoryError, stop Installation from wrapping one in a RuntimeException, and stop the Ktor client integration from swallowing coroutine cancellation while reading the response body. Refs JAVA-552 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent e6e5918 commit f9a4595

21 files changed

Lines changed: 193 additions & 32 deletions

File tree

‎sentry-android-core/src/main/java/io/sentry/android/core/AppState.java‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,8 @@ private void ensureLifecycleObserver(final @NotNull ILogger logger) {
112112
SentryLevel.WARNING,
113113
"androidx.lifecycle is not available, some features might not be properly working,"
114114
+ "e.g. Session Tracking, Network and System Events breadcrumbs, etc.");
115-
} catch (Throwable e) {
115+
} catch (LinkageError e) {
116+
// androidx.lifecycle has an incompatible version
116117
logger.log(SentryLevel.ERROR, "AppState could not register lifecycle observer", e);
117118
}
118119
}
@@ -124,7 +125,7 @@ private void addObserverInternal(final @NotNull ILogger logger) {
124125
if (observerRef != null) {
125126
ProcessLifecycleOwner.get().getLifecycle().addObserver(observerRef);
126127
}
127-
} catch (Throwable e) {
128+
} catch (LinkageError e) {
128129
// This is to handle a potential 'AbstractMethodError' gracefully. The error is triggered in
129130
// connection with conflicting dependencies of the androidx.lifecycle.
130131
// //See the issue here: https://github.com/getsentry/sentry-java/pull/2228

‎sentry-android-core/src/main/java/io/sentry/android/core/Installation.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ public static String id(final @NotNull Context context) throws RuntimeException
4343
return deviceId;
4444
}
4545
deviceId = readInstallationFile(installation);
46-
} catch (Throwable e) {
46+
} catch (IOException e) {
4747
throw new RuntimeException(e);
4848
}
4949
}

‎sentry-android-core/src/main/java/io/sentry/android/core/NdkIntegration.java‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,9 @@ public final void register(final @NotNull IScopes scopes, final @NotNull SentryO
8888
this.options
8989
.getLogger()
9090
.log(SentryLevel.ERROR, "Failed to invoke the SentryNdk.init method.", e);
91-
} catch (Throwable e) {
91+
} catch (ReflectiveOperationException e) {
92+
// InvocationTargetException wraps whatever SentryNdk.init threw, such as an
93+
// UnsatisfiedLinkError when the native library failed to load
9294
disableNdkIntegration(this.options);
9395
this.options.getLogger().log(SentryLevel.ERROR, "Failed to initialize SentryNdk.", e);
9496
}
@@ -120,7 +122,7 @@ public void close() throws IOException {
120122
options
121123
.getLogger()
122124
.log(SentryLevel.ERROR, "Failed to invoke the SentryNdk.close method.", e);
123-
} catch (Throwable e) {
125+
} catch (ReflectiveOperationException e) {
124126
options.getLogger().log(SentryLevel.ERROR, "Failed to close SentryNdk.", e);
125127
} finally {
126128
disableNdkIntegration(this.options);

‎sentry-android-core/src/main/java/io/sentry/android/core/ViewHierarchyEventProcessor.java‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,15 +189,29 @@ public static ViewHierarchy snapshotViewHierarchy(
189189
try {
190190
viewHierarchy.set(snapshotViewHierarchy(decorView, exporters));
191191
latch.countDown();
192+
} catch (LinkageError e) {
193+
// The Compose exporter calls Compose internals, which may not match the app's
194+
// Compose version
195+
logger.log(SentryLevel.ERROR, "Failed to process view hierarchy.", e);
192196
} catch (Throwable t) {
197+
// The snapshot calls into the app's own views, so we can't know what it throws.
198+
// The event is sent without a view hierarchy.
199+
ExceptionUtils.rethrowIfFatal(t);
193200
logger.log(SentryLevel.ERROR, "Failed to process view hierarchy.", t);
194201
}
195202
});
196203
if (latch.await(CAPTURE_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
197204
return viewHierarchy.get();
198205
}
199206
}
207+
} catch (LinkageError e) {
208+
// The Compose exporter calls Compose internals, which may not match the app's Compose
209+
// version
210+
logger.log(SentryLevel.ERROR, "Failed to process view hierarchy.", e);
200211
} catch (Throwable t) {
212+
// The snapshot calls into the app's own views, so we can't know what it throws. The event
213+
// is sent without a view hierarchy.
214+
ExceptionUtils.rethrowIfFatal(t);
201215
logger.log(SentryLevel.ERROR, "Failed to process view hierarchy.", t);
202216
}
203217
return null;

‎sentry-android-core/src/main/java/io/sentry/android/core/internal/gestures/SentryWindowCallback.java‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import io.sentry.SentryLevel;
77
import io.sentry.SentryOptions;
88
import io.sentry.SpanStatus;
9+
import io.sentry.util.ExceptionUtils;
910
import org.jetbrains.annotations.ApiStatus;
1011
import org.jetbrains.annotations.NotNull;
1112
import org.jetbrains.annotations.Nullable;
@@ -56,7 +57,16 @@ public boolean dispatchTouchEvent(final @Nullable MotionEvent motionEvent) {
5657
final MotionEvent copy = motionEventObtainer.obtain(motionEvent);
5758
try {
5859
handleTouchEvent(copy);
60+
} catch (LinkageError e) {
61+
// The Compose gesture locator calls Compose internals, which may not match the app's
62+
// Compose version
63+
if (options != null) {
64+
options.getLogger().log(SentryLevel.ERROR, "Error dispatching touch event", e);
65+
}
5966
} catch (Throwable e) {
67+
// Locating the touched view calls into the app's own views, so we can't know what it
68+
// throws. The gesture is not recorded, and the touch still reaches the app.
69+
ExceptionUtils.rethrowIfFatal(e);
6070
if (options != null) {
6171
options.getLogger().log(SentryLevel.ERROR, "Error dispatching touch event", e);
6272
}

‎sentry-android-ndk/src/main/java/io/sentry/android/ndk/DebugImagesLoader.java‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import io.sentry.ndk.NativeModuleListLoader;
99
import io.sentry.protocol.DebugImage;
1010
import io.sentry.util.AutoClosableReentrantLock;
11+
import io.sentry.util.ExceptionUtils;
1112
import io.sentry.util.Objects;
1213
import java.util.ArrayList;
1314
import java.util.HashSet;
@@ -71,7 +72,13 @@ public DebugImagesLoader(
7172
.getLogger()
7273
.log(SentryLevel.DEBUG, "Debug images loaded: %d", debugImages.size());
7374
}
75+
} catch (LinkageError e) {
76+
// e.g. UnsatisfiedLinkError when the native library failed to load
77+
options.getLogger().log(SentryLevel.ERROR, e, "Failed to load debug images.");
7478
} catch (Throwable e) {
79+
// A JNI call into sentry-native, so we can't know what it throws. The event is sent
80+
// without debug images.
81+
ExceptionUtils.rethrowIfFatal(e);
7582
options.getLogger().log(SentryLevel.ERROR, e, "Failed to load debug images.");
7683
}
7784
}
@@ -172,7 +179,13 @@ public void clearDebugImages() {
172179
moduleListLoader.clearModuleList();
173180

174181
options.getLogger().log(SentryLevel.INFO, "Debug images cleared.");
182+
} catch (LinkageError e) {
183+
// e.g. UnsatisfiedLinkError when the native library failed to load
184+
options.getLogger().log(SentryLevel.ERROR, e, "Failed to clear debug images.");
175185
} catch (Throwable e) {
186+
// A JNI call into sentry-native, so we can't know what it throws. The cached list is
187+
// cleared either way.
188+
ExceptionUtils.rethrowIfFatal(e);
176189
options.getLogger().log(SentryLevel.ERROR, e, "Failed to clear debug images.");
177190
}
178191
debugImages = null;

‎sentry-android-ndk/src/main/java/io/sentry/android/ndk/SentryNdk.java‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,9 @@ private SentryNdk() {}
2525
try {
2626
//noinspection UnstableApiUsage
2727
io.sentry.ndk.SentryNdk.loadNativeLibraries();
28-
} catch (Throwable t) {
29-
// ignored
30-
// if loadLibrary() fails, the later init() will throw an exception anyway
28+
} catch (LinkageError ignored) {
29+
// e.g. UnsatisfiedLinkError. The later init() throws too, which disables the NDK
30+
// integration.
3131
} finally {
3232
loadLibraryLatch.countDown();
3333
}

‎sentry-android-replay/src/main/java/io/sentry/android/replay/Windows.kt‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ internal object WindowSpy {
5353
lazy(NONE) {
5454
try {
5555
Class.forName("com.android.internal.policy.DecorView")
56-
} catch (ignored: Throwable) {
56+
} catch (ignored: ClassNotFoundException) {
5757
Log.d("WindowSpy", "Unexpected exception loading DecorView on API $SDK_INT", ignored)
5858
null
5959
}
@@ -171,7 +171,7 @@ internal object WindowManagerSpy {
171171
val className = "android.view.WindowManagerGlobal"
172172
try {
173173
Class.forName(className)
174-
} catch (ignored: Throwable) {
174+
} catch (ignored: ClassNotFoundException) {
175175
Log.w("WindowManagerSpy", ignored)
176176
null
177177
}
@@ -198,7 +198,10 @@ internal object WindowManagerSpy {
198198
mViewsField[windowManagerInstance] = swap(mViews)
199199
}
200200
}
201-
} catch (ignored: Throwable) {
201+
} catch (ignored: ReflectiveOperationException) {
202+
Log.w("WindowManagerSpy", ignored)
203+
} catch (ignored: ClassCastException) {
204+
// mViews is not an ArrayList on this device
202205
Log.w("WindowManagerSpy", ignored)
203206
}
204207
}

‎sentry-android-replay/src/main/java/io/sentry/android/replay/util/Nodes.kt‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import androidx.compose.ui.layout.LayoutCoordinates
3333
import androidx.compose.ui.layout.findRootCoordinates
3434
import androidx.compose.ui.node.LayoutNode
3535
import androidx.compose.ui.text.TextLayoutResult
36+
import io.sentry.util.ExceptionUtils
3637
import kotlin.math.ceil
3738
import kotlin.math.floor
3839
import kotlin.math.roundToInt
@@ -93,7 +94,7 @@ internal fun LayoutNode.findPainter(): Painter? {
9394
return try {
9495
modifier::class.java.getDeclaredField("painter").apply { isAccessible = true }.get(modifier)
9596
as? Painter
96-
} catch (e: Throwable) {
97+
} catch (_: ReflectiveOperationException) {
9798
null
9899
}
99100
}
@@ -136,7 +137,12 @@ internal fun LayoutNode.findTextColor(): Color? {
136137
(modifier::class.java.getDeclaredField("color").apply { isAccessible = true }.get(modifier)
137138
as? ColorProducer)
138139
?.invoke()
140+
} catch (_: LinkageError) {
141+
// older Compose versions don't have ColorProducer
142+
null
139143
} catch (e: Throwable) {
144+
// ColorProducer.invoke() runs the app's color lambda, so we can't know what it throws
145+
ExceptionUtils.rethrowIfFatal(e)
140146
null
141147
}
142148
}

‎sentry-android-replay/src/main/java/io/sentry/android/replay/viewhierarchy/ComposeViewHierarchyNode.kt‎

Lines changed: 32 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import io.sentry.android.replay.util.toRect
3232
import io.sentry.android.replay.viewhierarchy.ViewHierarchyNode.GenericViewHierarchyNode
3333
import io.sentry.android.replay.viewhierarchy.ViewHierarchyNode.ImageViewHierarchyNode
3434
import io.sentry.android.replay.viewhierarchy.ViewHierarchyNode.TextViewHierarchyNode
35+
import io.sentry.util.ExceptionUtils
3536
import java.lang.ref.WeakReference
3637
import java.lang.reflect.Method
3738

@@ -45,7 +46,7 @@ internal object ComposeViewHierarchyNode {
4546
.java
4647
.getDeclaredMethod("getCollapsedSemantics\$ui_release")
4748
.apply { isAccessible = true }
48-
} catch (_: Throwable) {
49+
} catch (_: NoSuchMethodException) {
4950
// ignore, as this method may not be available
5051
}
5152
return@lazy null
@@ -57,7 +58,7 @@ internal object ComposeViewHierarchyNode {
5758
internal fun retrieveSemanticsConfiguration(node: LayoutNode): SemanticsConfiguration? {
5859
return try {
5960
node.semanticsConfiguration
60-
} catch (t: Throwable) {
61+
} catch (t: NoSuchMethodError) {
6162
// for backwards compatibility
6263
// Jetpack Compose 1.8 or older
6364
if (getCollapsedSemanticsMethod != null) {
@@ -128,16 +129,27 @@ internal object ComposeViewHierarchyNode {
128129
}
129130

130131
val visibleRect = node.coordinates.boundsInWindow(_rootCoordinates?.get())
131-
val semantics: SemanticsConfiguration?
132+
var semanticsFailure: Throwable? = null
133+
val semantics: SemanticsConfiguration? =
134+
try {
135+
retrieveSemanticsConfiguration(node)
136+
} catch (e: LinkageError) {
137+
// an unsupported Compose version, which must not crash the app
138+
semanticsFailure = e
139+
null
140+
} catch (t: Throwable) {
141+
// semantics modifiers run app code, so we can't know what this throws
142+
ExceptionUtils.rethrowIfFatal(t)
143+
semanticsFailure = t
144+
null
145+
}
132146

133-
try {
134-
semantics = retrieveSemanticsConfiguration(node)
135-
} catch (t: Throwable) {
147+
if (semanticsFailure != null) {
136148
if (!semanticsRetrievalErrorLogged) {
137149
semanticsRetrievalErrorLogged = true
138150
logger.log(
139151
SentryLevel.ERROR,
140-
t,
152+
semanticsFailure,
141153
"""
142154
Error retrieving semantics information from Compose tree. Most likely you're using
143155
an unsupported version of androidx.compose.ui:ui. The supported
@@ -152,7 +164,7 @@ internal object ComposeViewHierarchyNode {
152164
// fail fast in our own sample/UI-test apps (see SentryReplayDebug), so regressions surface
153165
// as crashes instead of silently degrading masking
154166
if (SentryReplayDebug.failFast) {
155-
throw t
167+
throw semanticsFailure
156168
}
157169

158170
// If we're unable to retrieve the semantics configuration
@@ -284,13 +296,23 @@ internal object ComposeViewHierarchyNode {
284296
return false
285297
}
286298

299+
var traversalFailure: Throwable? = null
287300
try {
288301
val rootNode = (view as? Owner)?.root ?: return false
289302
rootNode.traverse(parent, isComposeRoot = true, options, logger)
303+
} catch (e: LinkageError) {
304+
// an unsupported Compose version, which must not crash the app
305+
traversalFailure = e
290306
} catch (e: Throwable) {
307+
// the traversal runs app code, so we can't know what it throws
308+
ExceptionUtils.rethrowIfFatal(e)
309+
traversalFailure = e
310+
}
311+
312+
if (traversalFailure != null) {
291313
logger.log(
292314
SentryLevel.ERROR,
293-
e,
315+
traversalFailure,
294316
"""
295317
Error traversing Compose tree. Most likely you're using an unsupported version of
296318
androidx.compose.ui:ui. The minimum supported version is 1.5.0. If it's a newer
@@ -302,7 +324,7 @@ internal object ComposeViewHierarchyNode {
302324
// fail fast in our own sample/UI-test apps (see SentryReplayDebug), so regressions surface
303325
// as crashes instead of silently skipping the whole Compose subtree (i.e. not masking it)
304326
if (SentryReplayDebug.failFast) {
305-
throw e
327+
throw traversalFailure
306328
}
307329
return false
308330
}

0 commit comments

Comments
 (0)