From 120662a037d6d3cdf4dddca671623f88ed4d19e8 Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Wed, 18 Nov 2026 17:16:19 +0100 Subject: [PATCH 1/5] fix: Rethrow fatal errors at the SDK's boundary catches The broad catches at boundaries, where we can't know what the other side throws, also swallowed OutOfMemoryError, StackOverflowError and LinkageError. They now call ExceptionUtils.rethrowIfFatal first, with a comment saying why the catch is broad and what is lost when it fails. The Javadoc of the user-facing callbacks says what happens when they throw. Sites where a LinkageError is the expected failure are left alone, so a missing or mismatched optional dependency keeps the old handling. Refs #5513 Refs JAVA-552 Co-Authored-By: Claude Opus 5.5 --- .../io/sentry/android/core/ANRWatchDog.java | 10 +- .../sentry/android/core/AnrV2Integration.java | 13 ++- .../AppComponentsBreadcrumbsIntegration.java | 14 ++- .../ApplicationExitInfoEventProcessor.java | 10 ++ .../io/sentry/android/core/ContextUtils.java | 35 +++++- .../core/DefaultAndroidEventProcessor.java | 4 + .../sentry/android/core/DeviceInfoUtil.java | 16 +++ .../core/EnvelopeFileObserverIntegration.java | 6 +- .../core/FeedbackShakeIntegration.java | 4 + .../android/core/InternalSentrySdk.java | 8 ++ .../android/core/ManifestMetadataReader.java | 8 ++ .../sentry/android/core/PerfettoProfiler.java | 4 + .../core/SendCachedEnvelopeIntegration.java | 5 + .../io/sentry/android/core/SentryAndroid.java | 15 ++- .../core/SentryPerformanceProvider.java | 6 ++ .../SystemEventsBreadcrumbsIntegration.java | 13 +++ .../android/core/TombstoneIntegration.java | 9 ++ .../core/ViewHierarchyEventProcessor.java | 4 +- .../core/anr/AnrProfilingIntegration.java | 4 + .../util/AndroidConnectionStatusProvider.java | 17 +++ .../core/internal/util/ScreenshotUtils.java | 14 ++- .../util/SentryFrameMetricsCollector.java | 12 +++ .../core/performance/AppStartMetrics.java | 7 +- .../io/sentry/android/core/ANRWatchDogTest.kt | 83 ++++++++++++++ .../android/core/AnrV2IntegrationTest.kt | 20 ++++ .../sentry/android/core/SentryAndroidTest.kt | 13 +++ .../sentry/android/ndk/NdkScopeObserver.java | 5 + .../io/sentry/android/replay/ReplayCache.kt | 4 + .../android/replay/ReplayIntegration.kt | 7 ++ .../android/replay/ScreenshotRecorder.kt | 4 + .../sentry/android/replay/WindowRecorder.kt | 4 + .../replay/gestures/GestureRecorder.kt | 5 + .../replay/screenshot/CanvasStrategy.kt | 4 + .../replay/screenshot/PixelCopyStrategy.kt | 7 ++ .../sentry/android/replay/util/Executors.kt | 5 + .../replay/util/ReplayExecutorService.kt | 5 + .../replay/video/SimpleVideoEncoder.kt | 4 + .../apollo3/SentryApollo3HttpInterceptor.kt | 14 +++ .../apollo3/SentryApollo3InterceptorTest.kt | 21 ++++ .../apollo4/SentryApollo4HttpInterceptor.kt | 14 +++ .../SentryApollo4HttpInterceptorTest.kt | 21 ++++ .../kafka/SentryKafkaConsumerTracing.java | 10 ++ .../io/sentry/kafka/SentryKafkaProducer.java | 8 ++ .../io/sentry/logback/SentryAppender.java | 16 ++- .../io/sentry/logback/SentryAppenderTest.kt | 17 +++ .../io/sentry/quartz/SentryJobListener.java | 7 ++ .../spotlight/SpotlightIntegration.java | 4 + .../sentry/spring7/SentryRequestResolver.java | 4 + .../io/sentry/spring7/SentrySpringFilter.java | 4 + .../sentry/spring7/checkin/SentryCheckIn.java | 5 + .../spring7/checkin/SentryCheckInAdvice.java | 4 + .../kafka/SentryKafkaRecordInterceptor.java | 4 + .../spring/jakarta/SentryRequestResolver.java | 4 + .../spring/jakarta/SentrySpringFilter.java | 4 + .../spring/jakarta/checkin/SentryCheckIn.java | 5 + .../jakarta/checkin/SentryCheckInAdvice.java | 4 + .../kafka/SentryKafkaRecordInterceptor.java | 4 + .../sentry/spring/SentryRequestResolver.java | 4 + .../io/sentry/spring/SentrySpringFilter.java | 4 + .../sentry/spring/checkin/SentryCheckIn.java | 5 + .../spring/checkin/SentryCheckInAdvice.java | 4 + .../kafka/SentryKafkaRecordInterceptor.java | 4 + .../java/io/sentry/DirectoryProcessor.java | 5 + .../main/java/io/sentry/EnvelopeSender.java | 4 + .../main/java/io/sentry/EventProcessor.java | 5 + sentry/src/main/java/io/sentry/IScopes.java | 22 ++++ .../src/main/java/io/sentry/Integration.java | 7 ++ .../main/java/io/sentry/JsonSerializer.java | 4 + .../src/main/java/io/sentry/OutboxSender.java | 7 ++ .../io/sentry/PreviousSessionFinalizer.java | 5 + .../java/io/sentry/ProfilingTraceData.java | 7 +- sentry/src/main/java/io/sentry/Scope.java | 3 + .../main/java/io/sentry/ScopeCallback.java | 11 ++ sentry/src/main/java/io/sentry/Scopes.java | 49 +++++++++ ...achedEnvelopeFireAndForgetIntegration.java | 5 + sentry/src/main/java/io/sentry/Sentry.java | 32 ++++++ .../src/main/java/io/sentry/SentryClient.java | 24 +++++ .../java/io/sentry/SentryEnvelopeItem.java | 5 + .../io/sentry/SentryEnvelopeItemHeader.java | 6 +- .../main/java/io/sentry/SentryOptions.java | 50 +++++++++ .../java/io/sentry/SentryReplayOptions.java | 10 ++ .../main/java/io/sentry/TracesSampler.java | 6 ++ .../UncaughtExceptionHandlerIntegration.java | 3 + .../java/io/sentry/cache/CacheStrategy.java | 7 ++ .../main/java/io/sentry/cache/CacheUtils.java | 7 ++ .../java/io/sentry/cache/EnvelopeCache.java | 11 ++ .../sentry/cache/PersistingScopeObserver.java | 7 ++ .../clientreport/ClientReportRecorder.java | 10 +- .../main/java/io/sentry/logger/LoggerApi.java | 8 ++ .../java/io/sentry/metrics/MetricsApi.java | 4 + .../io/sentry/transport/HttpConnection.java | 5 + .../io/sentry/transport/StdoutTransport.java | 5 +- .../sentry/util/EventSizeLimitingUtils.java | 6 ++ .../sentry/util/JsonSerializationUtils.java | 6 ++ sentry/src/test/java/io/sentry/ScopeTest.kt | 12 +++ sentry/src/test/java/io/sentry/ScopesTest.kt | 102 ++++++++++++++++++ .../test/java/io/sentry/SentryClientTest.kt | 9 ++ sentry/src/test/java/io/sentry/SentryTest.kt | 27 +++++ .../test/java/io/sentry/TracesSamplerTest.kt | 19 ++++ 99 files changed, 1096 insertions(+), 22 deletions(-) diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/ANRWatchDog.java b/sentry-android-core/src/main/java/io/sentry/android/core/ANRWatchDog.java index c109855daa7..62309dfc276 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/ANRWatchDog.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/ANRWatchDog.java @@ -34,6 +34,7 @@ import io.sentry.SentryLevel; import io.sentry.time.Deadline; import io.sentry.time.MonotonicTicker; +import io.sentry.util.ExceptionUtils; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -174,9 +175,16 @@ private boolean isProcessNotResponding() { if (am != null) { List processesInErrorState = null; try { - // It can throw RuntimeException or OutOfMemoryError processesInErrorState = am.getProcessesInErrorState(); + } catch (OutOfMemoryError e) { + // Unparceling the reply, which lists every process in an error state, can fail to + // allocate even when the app itself has memory left, so it's not treated as fatal here + // (#2114). The process is treated as responding normally, so no ANR is reported. + logger.log(SentryLevel.ERROR, "Error getting ActivityManager#getProcessesInErrorState.", e); } catch (Throwable e) { + // A Binder call into the activity manager, which can rethrow any runtime exception from + // the other side. The process is treated as responding normally, so no ANR is reported. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Error getting ActivityManager#getProcessesInErrorState.", e); } // if list is null, there's no process in ANR state. diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AnrV2Integration.java b/sentry-android-core/src/main/java/io/sentry/android/core/AnrV2Integration.java index 19de22c9a87..8926db2b48e 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AnrV2Integration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AnrV2Integration.java @@ -30,6 +30,7 @@ import io.sentry.protocol.SentryThread; import io.sentry.transport.CurrentDateProvider; import io.sentry.transport.ICurrentDateProvider; +import io.sentry.util.ExceptionUtils; import io.sentry.util.HintUtils; import io.sentry.util.Objects; import java.io.BufferedReader; @@ -204,8 +205,12 @@ public void markReported(final long timestamp) { return new ParseResult(ParseResult.Type.NO_DUMP); } dump = NativeEventUtils.readBytes(trace); - } catch (Throwable e) { - options.getLogger().log(SentryLevel.WARNING, "Failed to read ANR thread dump", e); + } catch (Throwable t) { + // getTraceInputStream() is a Binder call into system_server, which can rethrow any runtime + // exception from the other side. As with a missing dump, this ANR is not reported, and the + // remaining exit infos are still processed. + ExceptionUtils.rethrowIfFatal(t); + options.getLogger().log(SentryLevel.WARNING, "Failed to read ANR thread dump", t); return new ParseResult(ParseResult.Type.NO_DUMP); } @@ -229,6 +234,10 @@ public void markReported(final long timestamp) { } return new ParseResult(ParseResult.Type.DUMP, dump, threads, debugImages, artContext); } catch (Throwable e) { + // The dump is written by ART in a format that changes between Android versions and + // vendors, so we can't know how the parser fails on unexpected input. The ANR is still + // reported, with a message asking to attach the raw dump. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.WARNING, "Failed to parse ANR thread dump", e); return new ParseResult(ParseResult.Type.ERROR, dump); } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AppComponentsBreadcrumbsIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/AppComponentsBreadcrumbsIntegration.java index 66afe6033a3..f6dfded853d 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AppComponentsBreadcrumbsIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AppComponentsBreadcrumbsIntegration.java @@ -15,6 +15,7 @@ import io.sentry.android.core.internal.util.Debouncer; import io.sentry.android.core.internal.util.DeviceOrientations; import io.sentry.protocol.Device; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Objects; import java.io.Closeable; import java.io.IOException; @@ -66,6 +67,10 @@ public void register(final @NotNull IScopes scopes, final @NotNull SentryOptions .log(SentryLevel.DEBUG, "AppComponentsBreadcrumbsIntegration installed."); addIntegrationToSdkVersion("AppComponentsBreadcrumbs"); } catch (Throwable e) { + // The context may be the app's own subclass, or a ContextImpl that doesn't support + // component callbacks on older versions, so we can't know what this throws. App + // component breadcrumbs are disabled. + ExceptionUtils.rethrowIfFatal(e); this.options.setEnableAppComponentBreadcrumbs(false); options.getLogger().log(SentryLevel.INFO, e, "ComponentCallbacks2 is not available."); } @@ -77,12 +82,15 @@ public void close() throws IOException { try { // if its a ContextImpl, unregisterComponentCallbacks can't be used context.unregisterComponentCallbacks(this); - } catch (Throwable ignored) { - // fine, might throw on older versions + } catch (Throwable e) { + // The context may be the app's own subclass, or a ContextImpl that doesn't support + // component callbacks on older versions, so we can't know what this throws. The callbacks + // may stay registered until the process ends. + ExceptionUtils.rethrowIfFatal(e); if (options != null) { options .getLogger() - .log(SentryLevel.DEBUG, ignored, "It was not possible to unregisterComponentCallbacks"); + .log(SentryLevel.DEBUG, e, "It was not possible to unregisterComponentCallbacks"); } } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/ApplicationExitInfoEventProcessor.java b/sentry-android-core/src/main/java/io/sentry/android/core/ApplicationExitInfoEventProcessor.java index 63b08cb9b73..6bbe26ae7a1 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/ApplicationExitInfoEventProcessor.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/ApplicationExitInfoEventProcessor.java @@ -69,6 +69,7 @@ import io.sentry.protocol.SentryTransaction; import io.sentry.protocol.User; import io.sentry.protocol.profiling.SentryProfile; +import io.sentry.util.ExceptionUtils; import io.sentry.util.HintUtils; import io.sentry.util.SentryRandom; import java.io.File; @@ -447,6 +448,9 @@ private void setApp(final @NotNull SentryBaseEvent event) { } } } catch (Throwable e) { + // The first DeviceInfoUtil.getInstance call queries the package manager over Binder, which + // can rethrow any runtime exception from the other side. The split APK info is left out. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, "Error getting split apks info.", e); } @@ -716,6 +720,9 @@ private void setSideLoadedInfo(final @NotNull SentryBaseEvent event) { } } } catch (Throwable e) { + // The first DeviceInfoUtil.getInstance call queries the package manager over Binder, which + // can rethrow any runtime exception from the other side. The side-loaded tags are left out. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, "Error getting side loaded info.", e); } } @@ -975,6 +982,9 @@ private void applyAnrProfile( options.getLogger().log(SentryLevel.DEBUG, "No ANR profile file found"); } } catch (Throwable t) { + // The profile file was written by the previous process, possibly while it was being + // killed, so we can't know how reading it fails. The ANR is sent without a profile. + ExceptionUtils.rethrowIfFatal(t); options.getLogger().log(SentryLevel.INFO, "Could not retrieve ANR profile", t); } finally { if (!AnrProfileRotationHelper.deleteLastFile(cacheDir)) { diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/ContextUtils.java b/sentry-android-core/src/main/java/io/sentry/android/core/ContextUtils.java index 22938712faf..2350ec6bee5 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/ContextUtils.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/ContextUtils.java @@ -22,6 +22,7 @@ import io.sentry.SentryOptions; import io.sentry.android.core.util.AndroidLazyEvaluator; import io.sentry.protocol.App; +import io.sentry.util.ExceptionUtils; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; @@ -104,6 +105,9 @@ private ContextUtils() {} .getPackageManager() .getPackageInfo(context.getPackageName(), PackageManager.PackageInfoFlags.of(0)); } catch (Throwable e) { + // A Binder call into the package manager, which can rethrow any runtime exception from + // the other side. The package info is left out. + ExceptionUtils.rethrowIfFatal(e); return null; } }); @@ -113,6 +117,9 @@ private ContextUtils() {} try { return context.getPackageManager().getPackageInfo(context.getPackageName(), 0); } catch (Throwable e) { + // A Binder call into the package manager, which can rethrow any runtime exception from + // the other side. The package info is left out. + ExceptionUtils.rethrowIfFatal(e); return null; } }); @@ -131,6 +138,9 @@ private ContextUtils() {} return context.getString(stringId); } } catch (Throwable e) { + // getApplicationLabel is a Binder call into the package manager, and the context may be + // the app's own subclass, so we can't know what this throws. The app name is left out. + ExceptionUtils.rethrowIfFatal(e); return null; } }); @@ -150,6 +160,9 @@ private ContextUtils() {} context.getPackageName(), PackageManager.ApplicationInfoFlags.of(PackageManager.GET_META_DATA)); } catch (Throwable e) { + // A Binder call into the package manager, which can rethrow any runtime exception from + // the other side. The application info is left out. + ExceptionUtils.rethrowIfFatal(e); return null; } }); @@ -161,6 +174,9 @@ private ContextUtils() {} .getPackageManager() .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA); } catch (Throwable e) { + // A Binder call into the package manager, which can rethrow any runtime exception from + // the other side. The application info is left out. + ExceptionUtils.rethrowIfFatal(e); return null; } }); @@ -202,6 +218,9 @@ static PackageInfo getPackageInfo( return context.getPackageManager().getPackageInfo(context.getPackageName(), flags); } } catch (Throwable e) { + // A Binder call into the package manager, which can rethrow any runtime exception from the + // other side. The package info is left out. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Error getting package info.", e); return null; } @@ -269,8 +288,10 @@ public static boolean isForegroundImportance() { new ActivityManager.RunningAppProcessInfo(); ActivityManager.getMyMemoryState(appProcessInfo); return appProcessInfo.importance == IMPORTANCE_FOREGROUND; - } catch (Throwable ignored) { - // should never happen + } catch (Throwable e) { + // A Binder call into the activity manager, which can rethrow any runtime exception from the + // other side. The process is treated as not in the foreground. + ExceptionUtils.rethrowIfFatal(e); } return false; } @@ -299,7 +320,9 @@ public static boolean appIsLibraryForComposePreview(final @NotNull Context conte } } } catch (Throwable t) { - // ignored + // getAppTasks is a Binder call into the activity manager, which can rethrow any runtime + // exception from the other side. The app is treated as not running a Compose Preview. + ExceptionUtils.rethrowIfFatal(t); } } return false; @@ -398,6 +421,9 @@ public static boolean appIsLibraryForComposePreview(final @NotNull Context conte try { return context.getResources().getDisplayMetrics(); } catch (Throwable e) { + // The context may be the app's own subclass that overrides getResources(), so we can't know + // what it throws. The display metrics are left out. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Error getting DisplayMetrics.", e); return null; } @@ -440,6 +466,9 @@ public static boolean appIsLibraryForComposePreview(final @NotNull Context conte logger.log(SentryLevel.INFO, "Error getting MemoryInfo."); return null; } catch (Throwable e) { + // A Binder call into the activity manager, which can rethrow any runtime exception from the + // other side. The memory info is left out. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Error getting MemoryInfo.", e); return null; } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/DefaultAndroidEventProcessor.java b/sentry-android-core/src/main/java/io/sentry/android/core/DefaultAndroidEventProcessor.java index 5c28ccaf488..c12e8c36635 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/DefaultAndroidEventProcessor.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/DefaultAndroidEventProcessor.java @@ -17,6 +17,7 @@ import io.sentry.protocol.SentryThread; import io.sentry.protocol.SentryTransaction; import io.sentry.protocol.User; +import io.sentry.util.ExceptionUtils; import io.sentry.util.HintUtils; import io.sentry.util.Objects; import java.util.Collections; @@ -193,6 +194,9 @@ private void setDevice( .getContexts() .setDevice(deviceInfoUtil.get().collectDeviceInformation(errorEvent, applyScopeData)); } catch (Throwable e) { + // Collecting the device info makes Binder calls into several system services, which can + // rethrow any runtime exception from the other side. The device context is left out. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, "Failed to retrieve device info", e); } } else { diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/DeviceInfoUtil.java b/sentry-android-core/src/main/java/io/sentry/android/core/DeviceInfoUtil.java index 19113768ef3..784a8746ef0 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/DeviceInfoUtil.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/DeviceInfoUtil.java @@ -25,6 +25,7 @@ import io.sentry.android.core.internal.util.RootChecker; import io.sentry.protocol.Device; import io.sentry.protocol.OperatingSystem; +import io.sentry.util.ExceptionUtils; import java.io.File; import java.util.Calendar; import java.util.Collections; @@ -303,6 +304,9 @@ public static Float getBatteryLevel( return ((float) level / (float) scale) * percentMultiplier; } catch (Throwable e) { + // The extras were parceled by system_server and are unparceled on first access, which can + // throw any runtime exception on malformed data. The battery level is left out. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, "Error getting device battery level.", e); return null; } @@ -321,6 +325,9 @@ public static Boolean isCharging( return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB; } catch (Throwable e) { + // The extras were parceled by system_server and are unparceled on first access, which can + // throw any runtime exception on malformed data. The charging state is left out. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, "Error getting device charging state.", e); return null; } @@ -334,6 +341,9 @@ private Float getBatteryTemperature(final @NotNull Intent batteryIntent) { return ((float) temperature) / 10; // celsius } } catch (Throwable e) { + // The extras were parceled by system_server and are unparceled on first access, which can + // throw any runtime exception on malformed data. The temperature is left out. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, "Error getting battery temperature.", e); } return null; @@ -359,6 +369,9 @@ private Device.DeviceOrientation getOrientation() { return null; } } catch (Throwable e) { + // The context may be the app's own subclass that overrides getResources(), so we can't know + // what it throws. The orientation is left out. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, "Error getting device orientation.", e); } return deviceOrientation; @@ -394,6 +407,9 @@ private StatFs getExternalStorageStat(final @Nullable File internalStorage) { return new StatFs(path.getPath()); } } catch (Throwable e) { + // getExternalFilesDirs asks the storage service over Binder to create the directories, so + // we can't know what it throws. The external storage sizes are left out. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.INFO, "Not possible to read external files directory"); } return null; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/EnvelopeFileObserverIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/EnvelopeFileObserverIntegration.java index e81577cfd4b..fd60edfd50f 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/EnvelopeFileObserverIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/EnvelopeFileObserverIntegration.java @@ -10,6 +10,7 @@ import io.sentry.SentryLevel; import io.sentry.SentryOptions; import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.util.ExceptionUtils; import io.sentry.util.FileUtils; import io.sentry.util.Objects; import java.io.Closeable; @@ -92,7 +93,10 @@ private void startOutboxSender( options.getLogger().log(SentryLevel.DEBUG, "EnvelopeFileObserverIntegration installed."); addIntegrationToSdkVersion("EnvelopeFileObserver"); } catch (Throwable e) { - // it could throw eg NoSuchFileException or NullPointerException + // startWatching() sets up inotify through native code, which can throw e.g. + // NoSuchFileException or NullPointerException, so we can't know what it throws. Envelopes + // written to the outbox, e.g. by the NDK, are not picked up while the process runs. + ExceptionUtils.rethrowIfFatal(e); options .getLogger() .log(SentryLevel.ERROR, "Failed to initialize EnvelopeFileObserverIntegration.", e); diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/FeedbackShakeIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/FeedbackShakeIntegration.java index 677678b2438..8fce55f5079 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/FeedbackShakeIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/FeedbackShakeIntegration.java @@ -11,6 +11,7 @@ import io.sentry.SentryFeedbackOptions; import io.sentry.SentryLevel; import io.sentry.SentryOptions; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Objects; import java.io.Closeable; import java.io.IOException; @@ -298,6 +299,9 @@ private void startShakeDetection(final @NotNull Activity activity) { dialog = dialogFactory.create(active); dialog.show(); } catch (Throwable e) { + // show() adds a window over Binder and the dialog inflates with the app's theme, so + // we can't know what this throws. No dialog is shown for this shake. + ExceptionUtils.rethrowIfFatal(e); if (dialog != null) { onDialogGone(dialog); } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java b/sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java index 7c2e72031bb..84835bcb93c 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java @@ -30,6 +30,7 @@ import io.sentry.protocol.Device; import io.sentry.protocol.SentryId; import io.sentry.protocol.User; +import io.sentry.util.ExceptionUtils; import io.sentry.util.MapObjectWriter; import io.sentry.util.TracingUtils; import java.io.ByteArrayInputStream; @@ -139,6 +140,10 @@ public static Map serializeScope( writer.name("level").value(logger, scope.getLevel()); writer.name("breadcrumbs").value(logger, scope.getBreadcrumbs()); } catch (Throwable e) { + // An entry point for hybrid SDKs. Serializing the scope reaches into the device and package + // manager over Binder and into whatever objects the app put in extras, so we can't know what + // it throws. The caller gets an empty map. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, "Could not serialize scope.", e); return new HashMap<>(); } @@ -204,6 +209,9 @@ public static SentryId captureEnvelope( new SentryEnvelope(envelope.getHeader(), envelopeItems); return scopes.captureEnvelope(repackagedEnvelope); } catch (Throwable t) { + // An entry point for hybrid SDKs, which hand over an envelope we didn't build, so we can't + // know what processing it throws. The envelope is dropped and the caller gets null. + ExceptionUtils.rethrowIfFatal(t); options.getLogger().log(SentryLevel.ERROR, "Failed to capture envelope", t); } return null; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/ManifestMetadataReader.java b/sentry-android-core/src/main/java/io/sentry/android/core/ManifestMetadataReader.java index 411546a80b5..c24a2a8f6a9 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/ManifestMetadataReader.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/ManifestMetadataReader.java @@ -15,6 +15,7 @@ import io.sentry.SentryLevel; import io.sentry.SentryReplayOptions; import io.sentry.protocol.SdkVersion; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Objects; import java.util.ArrayList; import java.util.Arrays; @@ -842,6 +843,10 @@ static void applyMetadata( .getLogger() .log(SentryLevel.INFO, "Retrieving configuration from AndroidManifest.xml"); } catch (Throwable e) { + // A metadata bundle from the package manager is unparceled on first access, and its values + // are whatever the app put in its manifest, so we can't know what reading it throws. The + // options keep their defaults for every key not read yet. + ExceptionUtils.rethrowIfFatal(e); options .getLogger() .log( @@ -1134,6 +1139,9 @@ static boolean isAutoInit(final @NotNull Context context, final @NotNull ILogger autoInit = readBool(metadata, logger, AUTO_INIT, true); } } catch (Throwable e) { + // A metadata bundle from the package manager is unparceled on first access, so we can't know + // what reading it throws. Auto-init stays enabled. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Failed to read auto-init from android manifest metadata.", e); } return autoInit; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/PerfettoProfiler.java b/sentry-android-core/src/main/java/io/sentry/android/core/PerfettoProfiler.java index 4a64359aa44..c2df1e63137 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/PerfettoProfiler.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/PerfettoProfiler.java @@ -13,6 +13,7 @@ import io.sentry.SentryLevel; import io.sentry.android.core.internal.profiling.ChunkRecord; import io.sentry.profiling.ProfileRecordingState; +import io.sentry.util.ExceptionUtils; import java.io.File; import java.util.concurrent.RejectedExecutionException; import java.util.function.Consumer; @@ -109,6 +110,9 @@ boolean start(final @NotNull ChunkRecord chunkRecord, final long durationMs) { Runnable::run, this::onProfilingResult); } catch (Throwable e) { + // A Binder call into the profiling service, which can rethrow any runtime exception from + // the other side. This chunk is not profiled. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Failed to request Profiling.", e); // No profiling was requested, so a late result from the OS must not write into the record this.chunkRecord = null; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SendCachedEnvelopeIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/SendCachedEnvelopeIntegration.java index 1f3dc572792..9f40d7c4506 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SendCachedEnvelopeIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SendCachedEnvelopeIntegration.java @@ -12,6 +12,7 @@ import io.sentry.SentryOptions; import io.sentry.transport.RateLimiter; import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.util.ExceptionUtils; import io.sentry.util.LazyEvaluator; import io.sentry.util.Objects; import java.io.Closeable; @@ -136,6 +137,10 @@ private void sendCachedEnvelopes( sender.send(); } catch (Throwable e) { + // send() reads every envelope earlier processes left in the cache and hands them + // to the transport, so we can't know what it throws. The envelopes stay cached + // and are retried on the next connection change or app start. + ExceptionUtils.rethrowIfFatal(e); options .getLogger() .log(SentryLevel.ERROR, "Failed trying to send cached events.", e); 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..77542d7c044 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 @@ -151,7 +162,9 @@ public static void init( try { configuration.configure(options); } catch (Throwable t) { - // let it slip, but log it + // The configuration callback is the app'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-core/src/main/java/io/sentry/android/core/SentryPerformanceProvider.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryPerformanceProvider.java index d156b00fa5a..c9c72f9d8d2 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SentryPerformanceProvider.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SentryPerformanceProvider.java @@ -22,6 +22,7 @@ import io.sentry.android.core.internal.util.SentryFrameMetricsCollector; import io.sentry.android.core.performance.AppStartMetrics; import io.sentry.android.core.performance.TimeSpan; +import io.sentry.util.ExceptionUtils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; @@ -160,6 +161,11 @@ private void launchAppStartProfiler(final @NotNull AppStartMetrics appStartMetri } catch (FileNotFoundException e) { logger.log(SentryLevel.ERROR, "App start profiling config file not found. ", e); } catch (Throwable e) { + // Runs in a ContentProvider before Application.onCreate: it parses a config file written by + // the previous launch and starts a profiler through the platform's tracing, so we can't + // know what it throws, and it must not stop the app from starting. App start profiling + // doesn't start. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Error reading app start profiling config file. ", e); } } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SystemEventsBreadcrumbsIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/SystemEventsBreadcrumbsIntegration.java index b3caf622c37..e1c4966efb6 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SystemEventsBreadcrumbsIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SystemEventsBreadcrumbsIntegration.java @@ -37,6 +37,7 @@ import io.sentry.SentryOptions; import io.sentry.android.core.internal.util.Debouncer; import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Objects; import io.sentry.util.StringUtils; import java.io.Closeable; @@ -173,6 +174,10 @@ private void registerReceiver( addIntegrationToSdkVersion("SystemEventsBreadcrumbs"); } } catch (Throwable e) { + // registerReceiver is a Binder call into the activity manager, which can rethrow + // any runtime exception from the other side. System event breadcrumbs are + // disabled. + ExceptionUtils.rethrowIfFatal(e); options.setEnableSystemEventBreadcrumbs(false); options .getLogger() @@ -221,6 +226,10 @@ private void unregisterReceiver(final @NotNull SentryAndroidOptions options) { try { context.unregisterReceiver(receiverRef); } catch (Throwable exception) { + // unregisterReceiver is a Binder call into the activity manager, which can rethrow any + // runtime exception from the other side. The receiver may stay registered until the + // process ends. + ExceptionUtils.rethrowIfFatal(exception); options .getLogger() .log( @@ -409,6 +418,10 @@ String getStringAfterDotFast(final @Nullable String str) { newExtras.put(item, value.toString()); } } catch (Throwable exception) { + // The extras were parceled by the broadcast's sender and are unparceled here, and the + // value's class implements toString(), so we can't know what this throws. The extra + // is left out of the breadcrumb. + ExceptionUtils.rethrowIfFatal(exception); options .getLogger() .log( diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/TombstoneIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/TombstoneIntegration.java index 88f83fd2993..2a5158c131d 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/TombstoneIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/TombstoneIntegration.java @@ -35,6 +35,7 @@ import io.sentry.protocol.SentryThread; import io.sentry.transport.CurrentDateProvider; import io.sentry.transport.ICurrentDateProvider; +import io.sentry.util.ExceptionUtils; import io.sentry.util.HintUtils; import io.sentry.util.Objects; import java.io.ByteArrayInputStream; @@ -189,6 +190,10 @@ public void markReported(final long timestamp) { } } } catch (Throwable e) { + // getTraceInputStream() is a Binder call into system_server, and the tombstone was written + // by debuggerd for a crashing process, so we can't know what reading and parsing it + // throws. This tombstone is not reported. + ExceptionUtils.rethrowIfFatal(e); options .getLogger() .log( @@ -218,6 +223,10 @@ public void markReported(final long timestamp) { event = mergedEvent; } } catch (Throwable e) { + // The native events were written by sentry-native while the process was crashing, so we + // can't know what parsing and merging them throws. The tombstone is reported without + // them. + ExceptionUtils.rethrowIfFatal(e); options .getLogger() .log( 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..68f98c8a66e 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 @@ -268,7 +268,9 @@ private static ViewHierarchyNode viewToNode(@NotNull final View view) { node.setIdentifier(identifier); } } catch (Throwable e) { - // ignored + // The lookup goes through the view's context and resources, which the app's views can + // override, so we can't know what it throws. The node is sent without an identifier. + ExceptionUtils.rethrowIfFatal(e); } node.setX((double) view.getX()); node.setY((double) view.getY()); diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfilingIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfilingIntegration.java index 018fd49f6fd..0c7d3b39505 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfilingIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfilingIntegration.java @@ -17,6 +17,7 @@ import io.sentry.time.MonotonicTicker; import io.sentry.time.Stopwatch; import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Objects; import io.sentry.util.SentryRandom; import java.io.Closeable; @@ -224,6 +225,9 @@ public void run() { } } } catch (Throwable t) { + // The root of the profiling thread: anything escaping run() would reach the default + // uncaught exception handler and crash the app. Profiling stops until the next foreground. + ExceptionUtils.rethrowIfFatal(t); logger.log(SentryLevel.WARNING, "Failed to execute AnrStacktraceIntegration", t); } } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProvider.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProvider.java index de5a90c9067..45096ecce79 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProvider.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProvider.java @@ -23,6 +23,7 @@ import io.sentry.time.Deadline; import io.sentry.time.MonotonicTicker; import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.util.ExceptionUtils; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; @@ -553,6 +554,9 @@ private boolean hasSignificantTransportChanges( ? connectivityManager.getNetworkCapabilities(activeNetwork) : null; } catch (Throwable t) { + // Binder calls into the connectivity service, which can rethrow any runtime exception from + // the other side. The connection status stays unknown until the next refresh. + ExceptionUtils.rethrowIfFatal(t); options.getLogger().log(SentryLevel.WARNING, "Failed to update connection status cache", t); return null; } @@ -722,6 +726,9 @@ public NetworkCapabilities getCachedNetworkCapabilities() { ? ConnectionStatus.CONNECTED : ConnectionStatus.DISCONNECTED; } catch (Throwable t) { + // A Binder call into the connectivity service, which can rethrow any runtime exception from + // the other side. The status is reported as unknown. + ExceptionUtils.rethrowIfFatal(t); logger.log(SentryLevel.WARNING, "Could not retrieve Connection Status", t); return ConnectionStatus.UNKNOWN; } @@ -787,6 +794,9 @@ public NetworkCapabilities getCachedNetworkCapabilities() { return "cellular"; } } catch (Throwable exception) { + // Binder calls into the connectivity service, which can rethrow any runtime exception from + // the other side. The connection type is left out. + ExceptionUtils.rethrowIfFatal(exception); logger.log(SentryLevel.ERROR, "Failed to retrieve network info", exception); } @@ -877,6 +887,10 @@ static boolean registerNetworkCallback( connectivityManager.registerDefaultNetworkCallback(networkCallback); } } catch (Throwable t) { + // A Binder call into the connectivity service, which can rethrow any runtime exception from + // the other side, e.g. when the app has too many callbacks registered. Network changes are + // not observed. + ExceptionUtils.rethrowIfFatal(t); logger.log(SentryLevel.WARNING, "registerDefaultNetworkCallback failed", t); return false; } @@ -895,6 +909,9 @@ static void unregisterNetworkCallback( try { connectivityManager.unregisterNetworkCallback(networkCallback); } catch (Throwable t) { + // A Binder call into the connectivity service, which can rethrow any runtime exception from + // the other side. The callback may stay registered until the process ends. + ExceptionUtils.rethrowIfFatal(t); logger.log(SentryLevel.WARNING, "unregisterNetworkCallback failed", t); } } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/ScreenshotUtils.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/ScreenshotUtils.java index 1b17f28d5ed..7369ed3a00f 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/ScreenshotUtils.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/ScreenshotUtils.java @@ -15,6 +15,7 @@ import io.sentry.SentryLevel; import io.sentry.android.core.BuildInfoProvider; import io.sentry.android.core.SentryAndroidOptions; +import io.sentry.util.ExceptionUtils; import io.sentry.util.thread.IThreadChecker; import java.io.ByteArrayOutputStream; import java.util.concurrent.CountDownLatch; @@ -183,7 +184,9 @@ public final class ScreenshotUtils { final boolean completed = latch.await(CAPTURE_TIMEOUT_MS, TimeUnit.MILLISECONDS); success = completed && copyResultCode.get() == PixelCopy.SUCCESS; } catch (Throwable e) { - // ignored + // PixelCopy reads the window's surface through the system compositor, so we can't know + // what it throws. No screenshot is attached. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Taking screenshot using PixelCopy failed.", e); } finally { thread.quit(); @@ -206,6 +209,9 @@ public final class ScreenshotUtils { try { view.draw(canvas); } catch (Throwable e) { + // draw() runs the app's own views, so we can't know what it throws. No screenshot is + // attached. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Taking screenshot failed (view.draw).", e); } finally { latch.countDown(); @@ -219,6 +225,9 @@ public final class ScreenshotUtils { } return bitmap; } catch (Throwable e) { + // On the main thread, draw() runs the app's own views, so we can't know what it throws. No + // screenshot is attached. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Taking screenshot failed.", e); } return null; @@ -251,6 +260,9 @@ public final class ScreenshotUtils { // screenshot png is around ~100-150 kb return byteArrayOutputStream.toByteArray(); } catch (Throwable e) { + // compress() runs the native image encoder, so we can't know what it throws. No screenshot is + // attached. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Compressing bitmap failed.", e); } return null; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/SentryFrameMetricsCollector.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/SentryFrameMetricsCollector.java index 80d0ea08c1f..eccc20d59ad 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/SentryFrameMetricsCollector.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/SentryFrameMetricsCollector.java @@ -21,6 +21,7 @@ import io.sentry.android.core.ContextUtils; import io.sentry.android.core.SentryFramesDelayResult; import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Objects; import java.lang.ref.WeakReference; import java.lang.reflect.Field; @@ -129,6 +130,10 @@ public SentryFrameMetricsCollector( try { choreographer = Choreographer.getInstance(); } catch (Throwable e) { + // The first call creates the Choreographer, which connects to the display's vsync + // through native code, so we can't know what it throws. Slow and frozen frames are not + // reported. + ExceptionUtils.rethrowIfFatal(e); logger.log( SentryLevel.ERROR, "Error retrieving Choreographer instance. Slow and frozen frames will not be reported.", @@ -358,6 +363,9 @@ private void stopTrackingWindow(final @NotNull Window window) { window, frameMetricsAvailableListener); } } catch (Throwable e) { + // The window hands the listener to its native renderer, so we can't know what this + // throws. The listener may stay attached until the window is gone. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Failed to remove frameMetricsAvailableListener", e); } }); @@ -393,6 +401,10 @@ private void trackCurrentWindow() { windowFrameMetricsManager.addOnFrameMetricsAvailableListener( window, frameMetricsAvailableListener, handler); } catch (Throwable e) { + // The window hands the listener to its native renderer, so we can't know what this + // throws, e.g. for a window that isn't hardware accelerated. Frames of this window + // are not measured. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, "Failed to add frameMetricsAvailableListener", e); } } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/performance/AppStartMetrics.java b/sentry-android-core/src/main/java/io/sentry/android/core/performance/AppStartMetrics.java index 2eff6ffc787..50cb31d9fb4 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/performance/AppStartMetrics.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/performance/AppStartMetrics.java @@ -29,6 +29,7 @@ import io.sentry.android.core.internal.util.FirstDrawDoneListener; import io.sentry.protocol.SentryId; import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.util.ExceptionUtils; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -626,8 +627,10 @@ private void resolveHeadlessAppStartEndTime() { stopHeadlessAppStartAt(onCreateStartUptimeMs); return; } - } catch (Throwable ignored) { - // Best effort: never let optional startup timestamp enrichment break app startup. + } catch (Throwable e) { + // The start info came from system_server over Binder and the timestamp is optional, so a + // malformed record must not break app startup. The process init time is used instead. + ExceptionUtils.rethrowIfFatal(e); } } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/ANRWatchDogTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/ANRWatchDogTest.kt index fa0f8a7b2fa..dad5fa9c290 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/ANRWatchDogTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/ANRWatchDogTest.kt @@ -4,20 +4,27 @@ import android.app.ActivityManager import android.app.ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING import android.app.ActivityManager.ProcessErrorStateInfo.NO_ERROR import android.content.Context +import com.google.common.truth.Truth.assertThat import io.sentry.time.TestMonotonicTicker import java.util.concurrent.CountDownLatch +import java.util.concurrent.ExecutionException import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit.MILLISECONDS import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue import org.junit.Before import org.mockito.kotlin.any +import org.mockito.kotlin.atLeastOnce import org.mockito.kotlin.eq import org.mockito.kotlin.mock +import org.mockito.kotlin.mockingDetails +import org.mockito.kotlin.verify import org.mockito.kotlin.whenever class ANRWatchDogTest { @@ -229,6 +236,82 @@ class ANRWatchDogTest { } } + @Test + fun `when getProcessesInErrorState runs out of memory, keeps watching without reporting`() { + var anr: ApplicationNotResponding? = null + val am = mock() + whenever(am.processesInErrorState).thenThrow(OutOfMemoryError("large reply")) + val posted = CountDownLatch(1) + val sut = watchDog(am, posted) { a -> anr = a } + val es = Executors.newSingleThreadExecutor() + try { + val running = es.submit { sut.run() } + assertTrue(posted.await(10L, TimeUnit.SECONDS)) + + var waitCount = 0 + do { + ticker.advance(100, MILLISECONDS) + Thread.sleep(100L) + } while (mockingDetails(am).invocations.isEmpty() && waitCount++ < 100) + + verify(am, atLeastOnce()).processesInErrorState + assertNull(anr) + assertFalse(running.isDone) + } finally { + sut.interrupt() + es.shutdown() + } + } + + @Test + fun `when getProcessesInErrorState throws a fatal error, the watchdog stops`() { + val am = mock() + whenever(am.processesInErrorState).thenThrow(StackOverflowError()) + val posted = CountDownLatch(1) + val sut = watchDog(am, posted) {} + val es = Executors.newSingleThreadExecutor() + try { + val running = es.submit { sut.run() } + assertTrue(posted.await(10L, TimeUnit.SECONDS)) + + var waitCount = 0 + do { + ticker.advance(100, MILLISECONDS) + Thread.sleep(100L) + } while (!running.isDone && waitCount++ < 100) + + val error = assertFailsWith { running.get() } + assertThat(error.cause).isInstanceOf(StackOverflowError::class.java) + } finally { + sut.interrupt() + es.shutdown() + } + } + + private fun watchDog( + am: ActivityManager, + posted: CountDownLatch, + listener: ANRWatchDog.ANRListener, + ): ANRWatchDog { + val handler = mock() + // the posted runnable never runs, so the main thread looks blocked + whenever(handler.post(any())).then { posted.countDown() } + whenever(handler.thread).thenReturn(mock()) + val context = mock() + whenever(context.getSystemService(eq(Context.ACTIVITY_SERVICE))).thenReturn(am) + return ANRWatchDog( + ticker, + 10L, + 1L, + true, + listener, + mock(), + handler, + context, + AndroidDebugManager(), + ) + } + @Test fun `measures the ANR threshold on the ticker, not on wall time`() { var anr: ApplicationNotResponding? = null diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/AnrV2IntegrationTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AnrV2IntegrationTest.kt index 5d43c28ede3..8c78fe22897 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/AnrV2IntegrationTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/AnrV2IntegrationTest.kt @@ -237,6 +237,26 @@ class AnrV2IntegrationTest : ApplicationExitIntegrationTestBase() { verify(fixture.scopes, never()).captureEvent(any(), anyOrNull()) } + @Test + fun `when reading the trace throws a runtime exception, does not report ANR`() { + val integration = fixture.getSut(tmpDir, lastReportedTimestamp = oldTimestamp) + val exitInfo = + spy( + ApplicationExitInfoBuilder.newBuilder() + .setReason(ApplicationExitInfo.REASON_ANR) + .setTimestamp(newTimestamp) + .build(), + ) { + // getTraceInputStream() is a Binder call, which rethrows exceptions from system_server + whenever(mock.traceInputStream).thenThrow(SecurityException("denied")) + } + fixture.shadowActivityManager.addApplicationExitInfo(exitInfo) + + integration.register(fixture.scopes, fixture.options) + + verify(fixture.scopes, never()).captureEvent(any(), anyOrNull()) + } + @Test fun `when traceInputStream has bad data, does not report ANR`() { val integration = fixture.getSut(tmpDir, lastReportedTimestamp = oldTimestamp) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt index dc2472e6a6d..b400bb4707c 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt @@ -217,6 +217,19 @@ class SentryAndroidTest { assertTrue(Sentry.isEnabled()) } + @Test + fun `when the configuration handler throws, init continues with the options it set`() { + var refOptions: SentryAndroidOptions? = null + fixture.initSut { + it.anrTimeoutIntervalMillis = 3000 + refOptions = it + throw IllegalStateException("configuration failed") + } + + assertEquals(3000, refOptions!!.anrTimeoutIntervalMillis) + assertTrue(Sentry.isEnabled()) + } + @Test fun `init won't throw exception`() { val logger = mock() diff --git a/sentry-android-ndk/src/main/java/io/sentry/android/ndk/NdkScopeObserver.java b/sentry-android-ndk/src/main/java/io/sentry/android/ndk/NdkScopeObserver.java index 0ec3446aa83..3d409eca87e 100644 --- a/sentry-android-ndk/src/main/java/io/sentry/android/ndk/NdkScopeObserver.java +++ b/sentry-android-ndk/src/main/java/io/sentry/android/ndk/NdkScopeObserver.java @@ -11,6 +11,7 @@ import io.sentry.ndk.INativeScope; import io.sentry.ndk.NativeScope; import io.sentry.protocol.User; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Objects; import java.util.Locale; import java.util.Map; @@ -81,6 +82,10 @@ public void addBreadcrumb(final @NotNull Breadcrumb crumb) { data = options.getSerializer().serialize(dataRef); } } catch (Throwable e) { + // The data can hold any object the app put there, and the serializer reads it + // reflectively, so we can't know what it throws. The breadcrumb is synced to the + // native scope without its data. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, e, "Breadcrumb data is not serializable."); } diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayCache.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayCache.kt index 64aec8a077c..0e571379a7d 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayCache.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayCache.kt @@ -17,6 +17,7 @@ import io.sentry.protocol.SdkVersion import io.sentry.protocol.SentryId import io.sentry.rrweb.RRWebEvent import io.sentry.util.AutoClosableReentrantLock +import io.sentry.util.ExceptionUtils import io.sentry.util.FileUtils import java.io.Closeable import java.io.File @@ -232,6 +233,9 @@ public class ReplayCache(private val options: SentryOptions, private val replayI bitmap.recycle() true } catch (e: Throwable) { + // The encoder goes through the device's MediaCodec, so we can't know what it throws. The + // frame is left out of the video. + ExceptionUtils.rethrowIfFatal(e) options.logger.log( WARNING, "Unable to decode bitmap and encode it into a video, skipping frame", 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..898b3070d80 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 @@ -487,6 +488,9 @@ public class ReplayIntegration( hint.set(TypeCheckHint.REPLAY_FRAME_BITMAP, copy) observer.onMaskedFrameCaptured(hint, frameTimeStamp, screen) } 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() } @@ -510,6 +514,9 @@ public class ReplayIntegration( hint.set(TypeCheckHint.REPLAY_FRAME_BITMAP, bitmap) observer.onMaskedFrameCaptured(hint, frameTimestamp, screen) } 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-android-replay/src/main/java/io/sentry/android/replay/ScreenshotRecorder.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/ScreenshotRecorder.kt index ce987c24ce8..bbbdf3e1460 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/ScreenshotRecorder.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/ScreenshotRecorder.kt @@ -17,6 +17,7 @@ import io.sentry.android.replay.screenshot.ScreenshotStrategy import io.sentry.android.replay.util.DebugOverlayDrawable import io.sentry.android.replay.util.addOnDrawListenerSafe import io.sentry.android.replay.util.removeOnDrawListenerSafe +import io.sentry.util.ExceptionUtils import java.io.File import java.lang.ref.WeakReference import java.util.concurrent.atomic.AtomicBoolean @@ -92,6 +93,9 @@ internal class ScreenshotRecorder( contentChanged.set(false) screenshotStrategy.capture(root) } catch (e: Throwable) { + // Capturing draws the app's own views and goes through the device's graphics stack, so we + // can't know what it throws. The frame is skipped. + ExceptionUtils.rethrowIfFatal(e) options.logger.log(WARNING, "Failed to capture replay recording", e) } } diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/WindowRecorder.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/WindowRecorder.kt index 8ee0041f8b1..52ce2af4c7b 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/WindowRecorder.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/WindowRecorder.kt @@ -16,6 +16,7 @@ import io.sentry.android.replay.util.addOnPreDrawListenerSafe import io.sentry.android.replay.util.hasSize import io.sentry.android.replay.util.removeOnPreDrawListenerSafe import io.sentry.util.AutoClosableReentrantLock +import io.sentry.util.ExceptionUtils import java.lang.ref.WeakReference import java.util.WeakHashMap import java.util.concurrent.ScheduledExecutorService @@ -96,6 +97,9 @@ internal class WindowRecorder( } recorder?.capture() } catch (e: Throwable) { + // Capturing draws the app's own views and goes through the device's graphics stack, so we + // can't know what it throws. This frame is skipped, and the next one is still scheduled. + ExceptionUtils.rethrowIfFatal(e) options.logger.log(ERROR, "Failed to capture a frame", e) } diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/gestures/GestureRecorder.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/gestures/GestureRecorder.kt index cee75fb06c0..ff3ed2e1c2b 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/gestures/GestureRecorder.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/gestures/GestureRecorder.kt @@ -10,6 +10,7 @@ import io.sentry.android.replay.OnRootViewsChangedListener import io.sentry.android.replay.phoneWindow import io.sentry.android.replay.util.FixedWindowCallback import io.sentry.util.AutoClosableReentrantLock +import io.sentry.util.ExceptionUtils import java.lang.ref.WeakReference import java.util.WeakHashMap @@ -99,6 +100,10 @@ internal class GestureRecorder( try { touchRecorderCallback?.onTouchEvent(copy) } catch (e: Throwable) { + // This runs inside the app's touch dispatch, so a failure while recording the gesture + // must not cost the app its touch. The gesture is missing from the replay, and the touch + // still reaches the app below. + ExceptionUtils.rethrowIfFatal(e) options.logger.log(ERROR, "Error dispatching touch event", e) } finally { copy.recycle() diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/screenshot/CanvasStrategy.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/screenshot/CanvasStrategy.kt index dfb8ec0f268..2b24f984be9 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/screenshot/CanvasStrategy.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/screenshot/CanvasStrategy.kt @@ -36,6 +36,7 @@ import io.sentry.android.replay.ScreenshotRecorderCallback import io.sentry.android.replay.ScreenshotRecorderConfig import io.sentry.android.replay.util.ReplayRunnable import io.sentry.util.AutoClosableReentrantLock +import io.sentry.util.ExceptionUtils import io.sentry.util.IntegrationUtils import java.util.WeakHashMap import java.util.concurrent.atomic.AtomicBoolean @@ -144,6 +145,9 @@ internal class CanvasStrategy( executor.getBackgroundHandler(), ) } catch (t: Throwable) { + // Drawing into the hardware surface and PixelCopy go through the device's graphics stack, + // so we can't know what they throw. The frame is skipped. + ExceptionUtils.rethrowIfFatal(t) // if the request itself threw, no callback will clear the flag pixelCopyInFlight = false options.logger.log(SentryLevel.ERROR, "Canvas Strategy: picture render failed", t) diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/screenshot/PixelCopyStrategy.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/screenshot/PixelCopyStrategy.kt index 72c355a5a70..3a2da50cb8f 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/screenshot/PixelCopyStrategy.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/screenshot/PixelCopyStrategy.kt @@ -24,6 +24,7 @@ import io.sentry.android.replay.util.MaskRenderer import io.sentry.android.replay.util.ReplayRunnable import io.sentry.android.replay.util.traverse import io.sentry.android.replay.viewhierarchy.ViewHierarchyNode +import io.sentry.util.ExceptionUtils import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger import kotlin.LazyThreadSafetyMode.NONE @@ -177,6 +178,9 @@ internal class PixelCopyStrategy( mainLooperHandler.handler, ) } catch (e: Throwable) { + // PixelCopy goes through the device's graphics stack, so we can't know what it throws. The + // frame is skipped, and the frame gate is released for the next one. + ExceptionUtils.rethrowIfFatal(e) options.logger.log(WARNING, "Failed to capture replay recording", e) unstableCaptures.set(0) lastCaptureSuccessful.set(false) @@ -294,6 +298,9 @@ internal class PixelCopyStrategy( // double-recycle if the recycle paths above already ran. svBitmap = null } catch (e: Throwable) { + // PixelCopy goes through the device's graphics stack, so we can't know what it throws. + // This SurfaceView is left out of the frame. + ExceptionUtils.rethrowIfFatal(e) options.logger.log(WARNING, "Failed to capture SurfaceView", e) svBitmap?.recycle() onCaptureComplete() diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/util/Executors.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/util/Executors.kt index a5dddc3bd4d..10bc76b21bd 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/util/Executors.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/util/Executors.kt @@ -3,6 +3,7 @@ package io.sentry.android.replay.util import io.sentry.ISentryExecutorService import io.sentry.SentryLevel.ERROR import io.sentry.SentryOptions +import io.sentry.util.ExceptionUtils import java.util.concurrent.Future internal fun ISentryExecutorService.submitSafely( @@ -15,6 +16,10 @@ internal fun ISentryExecutorService.submitSafely( try { task.run() } catch (e: Throwable) { + // The tasks decode frames and encode video through the device's media stack, so we can't + // know what they throw. The failure is logged here because nobody reads the returned + // future, and the task's work is lost. + ExceptionUtils.rethrowIfFatal(e) options.logger.log(ERROR, "Failed to execute task $taskName", e) } } diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/util/ReplayExecutorService.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/util/ReplayExecutorService.kt index 5ba334f8029..bbb7fc2b860 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/util/ReplayExecutorService.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/util/ReplayExecutorService.kt @@ -2,6 +2,7 @@ package io.sentry.android.replay.util import io.sentry.SentryLevel.ERROR import io.sentry.SentryOptions +import io.sentry.util.ExceptionUtils import java.util.concurrent.Future import java.util.concurrent.ScheduledExecutorService import java.util.concurrent.TimeUnit @@ -35,6 +36,10 @@ internal class ReplayExecutorService( try { task.run() } catch (e: Throwable) { + // Replay's tasks mask frames, write the cache, and encode video through the device's + // graphics and media stacks, so we can't know what they throw. The failure is logged + // here because nobody reads the returned future, and that task's work is lost. + ExceptionUtils.rethrowIfFatal(e) options.logger.log( ERROR, "Failed to execute task ${if (task is ReplayRunnable) task.taskName else ""}", diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/video/SimpleVideoEncoder.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/video/SimpleVideoEncoder.kt index e8b77b0994c..a14fbca2085 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/video/SimpleVideoEncoder.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/video/SimpleVideoEncoder.kt @@ -40,6 +40,7 @@ import io.sentry.SentryLevel.DEBUG import io.sentry.SentryLevel.WARNING import io.sentry.SentryOptions import io.sentry.android.replay.util.SystemProperties +import io.sentry.util.ExceptionUtils import java.io.File import java.nio.ByteBuffer import kotlin.LazyThreadSafetyMode.NONE @@ -100,6 +101,9 @@ internal class SimpleVideoEncoder( bitRate = videoCapabilities.bitrateRange.clamp(bitRate) } } catch (e: Throwable) { + // The codec's capabilities come from the device's media framework, so we can't know what + // it throws. The bit rate is used without clamping it to the supported range. + ExceptionUtils.rethrowIfFatal(e) options.logger.log(DEBUG, "Could not retrieve MediaCodec info", e) } 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..3cbf323e712 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 @@ -229,6 +230,9 @@ constructor( span.spanContext.sampled = false } } 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) span.spanContext.sampled = false if (wasSampled) { scopes.options.clientReportRecorder.recordLostEvent( @@ -434,6 +438,9 @@ constructor( it.writeTo(buffer) data = GraphqlUtils.filterRequestBody(buffer.readUtf8(), scopes.options) } 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 { @@ -466,6 +473,9 @@ constructor( scopes.captureEvent(event, hint) } 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 +485,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-3/src/test/java/io/sentry/apollo3/SentryApollo3InterceptorTest.kt b/sentry-apollo-3/src/test/java/io/sentry/apollo3/SentryApollo3InterceptorTest.kt index 7b9454f394a..f18bc20a8ad 100644 --- a/sentry-apollo-3/src/test/java/io/sentry/apollo3/SentryApollo3InterceptorTest.kt +++ b/sentry-apollo-3/src/test/java/io/sentry/apollo3/SentryApollo3InterceptorTest.kt @@ -484,6 +484,27 @@ class SentryApollo3InterceptorTest { ) } + @Test + fun `when beforeSpan throws a fatal error, rethrows it`(): Unit = runBlocking { + val tx = + SentryTracer(TransactionContext("op", "desc", TracesSamplingDecision(true)), fixture.scopes) + whenever(fixture.scopes.span).thenReturn(tx) + val chain = + object : HttpInterceptorChain { + override suspend fun proceed(request: HttpRequest): HttpResponse = + HttpResponse.Builder(200).build() + } + val request = HttpRequest.Builder(HttpMethod.Post, "https://example.com/graphql").build() + val interceptor = + SentryApollo3HttpInterceptor( + fixture.scopes, + { _, _, _ -> throw OutOfMemoryError("callback") }, + captureFailedRequests = false, + ) + + assertFailsWith { interceptor.intercept(request, chain) } + } + @Test fun `adds breadcrumb when http calls succeeds`() { executeQuery(fixture.getSut()) 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..6610f331c46 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 @@ -228,6 +229,9 @@ constructor( span.spanContext.sampled = false } } 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) span.spanContext.sampled = false if (wasSampled) { scopes.options.clientReportRecorder.recordLostEvent( @@ -433,6 +437,9 @@ constructor( it.writeTo(buffer) data = GraphqlUtils.filterRequestBody(buffer.readUtf8(), scopes.options) } 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,6 +472,9 @@ constructor( scopes.captureEvent(event, hint) } 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 +484,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/test/java/io/sentry/apollo4/SentryApollo4HttpInterceptorTest.kt b/sentry-apollo-4/src/test/java/io/sentry/apollo4/SentryApollo4HttpInterceptorTest.kt index cb78ddcbd05..b32c822981a 100644 --- a/sentry-apollo-4/src/test/java/io/sentry/apollo4/SentryApollo4HttpInterceptorTest.kt +++ b/sentry-apollo-4/src/test/java/io/sentry/apollo4/SentryApollo4HttpInterceptorTest.kt @@ -498,6 +498,27 @@ abstract class SentryApollo4HttpInterceptorTest( ) } + @Test + fun `when beforeSpan throws a fatal error, rethrows it`(): Unit = runBlocking { + val tx = + SentryTracer(TransactionContext("op", "desc", TracesSamplingDecision(true)), fixture.scopes) + whenever(fixture.scopes.span).thenReturn(tx) + val chain = + object : HttpInterceptorChain { + override suspend fun proceed(request: HttpRequest): HttpResponse = + HttpResponse.Builder(200).build() + } + val request = HttpRequest.Builder(HttpMethod.Post, "https://example.com/graphql").build() + val interceptor = + SentryApollo4HttpInterceptor( + fixture.scopes, + { _, _, _ -> throw OutOfMemoryError("callback") }, + captureFailedRequests = false, + ) + + assertFailsWith { interceptor.intercept(request, chain) } + } + @Test fun `adds breadcrumb when http calls succeeds`() { executeQuery(fixture.getSut()) diff --git a/sentry-kafka/src/main/java/io/sentry/kafka/SentryKafkaConsumerTracing.java b/sentry-kafka/src/main/java/io/sentry/kafka/SentryKafkaConsumerTracing.java index 15e97b3663d..0c69104284d 100644 --- a/sentry-kafka/src/main/java/io/sentry/kafka/SentryKafkaConsumerTracing.java +++ b/sentry-kafka/src/main/java/io/sentry/kafka/SentryKafkaConsumerTracing.java @@ -12,6 +12,7 @@ import io.sentry.SpanStatus; import io.sentry.TransactionContext; import io.sentry.TransactionOptions; +import io.sentry.util.ExceptionUtils; import io.sentry.util.SpanUtils; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; @@ -85,6 +86,9 @@ U withTracingImpl( forkedScopes = scopes.forkedRootScopes(CREATOR); lifecycleToken = forkedScopes.makeCurrent(); } catch (Throwable t) { + // Tracing must never stop the app from processing the record. The record is processed + // without a transaction. + ExceptionUtils.rethrowIfFatal(t); scopes .getOptions() .getLogger() @@ -181,6 +185,9 @@ private boolean isIgnored() { return transaction; } catch (Throwable t) { + // This parses headers written by whichever producer sent the record, and tracing must never + // stop the app from processing it. The record is processed without a transaction. + ExceptionUtils.rethrowIfFatal(t); scopes .getOptions() .getLogger() @@ -204,6 +211,9 @@ private void finishTransaction( } transaction.finish(); } catch (Throwable t) { + // finish() runs the event processors and beforeSendTransaction, which can be the app's own + // code, and the record's processing result must stand. The transaction is not sent. + ExceptionUtils.rethrowIfFatal(t); scopes .getOptions() .getLogger() diff --git a/sentry-kafka/src/main/java/io/sentry/kafka/SentryKafkaProducer.java b/sentry-kafka/src/main/java/io/sentry/kafka/SentryKafkaProducer.java index 4ea3853977e..3e3050c9d57 100644 --- a/sentry-kafka/src/main/java/io/sentry/kafka/SentryKafkaProducer.java +++ b/sentry-kafka/src/main/java/io/sentry/kafka/SentryKafkaProducer.java @@ -10,6 +10,7 @@ import io.sentry.SpanDataConvention; import io.sentry.SpanOptions; import io.sentry.SpanStatus; +import io.sentry.util.ExceptionUtils; import io.sentry.util.SpanUtils; import io.sentry.util.TracingUtils; import java.lang.reflect.InvocationHandler; @@ -186,6 +187,9 @@ static final class SentryProducerHandler implements InvocationHandler { span.setStatus(SpanStatus.OK); } } catch (Throwable t) { + // This runs on Kafka's I/O thread for every send, and a tracing failure must not reach + // the producer. The span finishes without a status, and the app's callback still runs. + ExceptionUtils.rethrowIfFatal(t); scopes .getOptions() .getLogger() @@ -242,6 +246,10 @@ private void maybeInjectHeaders(final @NotNull Headers headers, final @Nullable .toString() .getBytes(StandardCharsets.UTF_8)); } catch (Throwable t) { + // The record and its headers come from the app, e.g. read-only headers of a record that + // was already sent, so we can't know what they throw. The record is sent without Sentry + // headers. + ExceptionUtils.rethrowIfFatal(t); scopes .getOptions() .getLogger() 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..f52110ffdc5 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,9 @@ 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. + // The event falls back to the default formatted message. + ExceptionUtils.rethrowIfFatal(t); addWarn("Failed to encode logging event", t); } } @@ -347,6 +349,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-logback/src/test/kotlin/io/sentry/logback/SentryAppenderTest.kt b/sentry-logback/src/test/kotlin/io/sentry/logback/SentryAppenderTest.kt index a5ecb2b30cd..04b3a97da14 100644 --- a/sentry-logback/src/test/kotlin/io/sentry/logback/SentryAppenderTest.kt +++ b/sentry-logback/src/test/kotlin/io/sentry/logback/SentryAppenderTest.kt @@ -32,6 +32,7 @@ import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull @@ -329,6 +330,22 @@ class SentryAppenderTest { ) } + class FatalEncoder : EncoderBase() { + override fun headerBytes(): ByteArray = ByteArray(0) + + override fun footerBytes(): ByteArray = ByteArray(0) + + override fun encode(event: ILoggingEvent?): ByteArray = throw OutOfMemoryError("encoder") + } + + @Test + fun `rethrows a fatal error from the encoder`() { + fixture = + Fixture(minimumEventLevel = Level.DEBUG, encoder = FatalEncoder(), sendDefaultPii = true) + + assertFailsWith { fixture.logger.info("testing a fatal encoder error") } + } + @Test fun `event date is in UTC`() { fixture = Fixture(minimumEventLevel = Level.DEBUG) diff --git a/sentry-quartz/src/main/java/io/sentry/quartz/SentryJobListener.java b/sentry-quartz/src/main/java/io/sentry/quartz/SentryJobListener.java index 5d48cbbaf87..f28b6c735f8 100644 --- a/sentry-quartz/src/main/java/io/sentry/quartz/SentryJobListener.java +++ b/sentry-quartz/src/main/java/io/sentry/quartz/SentryJobListener.java @@ -10,6 +10,7 @@ import io.sentry.SentryIntegrationPackageStorage; import io.sentry.SentryLevel; import io.sentry.protocol.SentryId; +import io.sentry.util.ExceptionUtils; import io.sentry.util.LifecycleHelper; import io.sentry.util.MonitorConfigUtils; import io.sentry.util.Objects; @@ -92,6 +93,9 @@ public void jobToBeExecuted(final @NotNull JobExecutionContext context) { context.put(SENTRY_CHECK_IN_ID_KEY, checkInId); context.put(SENTRY_SLUG_KEY, slug); } catch (Throwable t) { + // This reads the app's job data and trigger, and Quartz doesn't run the job when a listener + // throws, so we can't let anything escape. The job runs without a check-in. + ExceptionUtils.rethrowIfFatal(t); scopes .getOptions() .getLogger() @@ -281,6 +285,9 @@ public void jobWasExecuted(JobExecutionContext context, JobExecutionException jo scopes.captureCheckIn(new CheckIn(checkInId, slug, status)); } } catch (Throwable t) { + // This runs on Quartz's job thread after the app's job, which a reporting failure must not + // disturb. The check-in for this run is not sent. + ExceptionUtils.rethrowIfFatal(t); scopes .getOptions() .getLogger() diff --git a/sentry-spotlight/src/main/java/io/sentry/spotlight/SpotlightIntegration.java b/sentry-spotlight/src/main/java/io/sentry/spotlight/SpotlightIntegration.java index ac8916cd08c..c1a60848aa7 100644 --- a/sentry-spotlight/src/main/java/io/sentry/spotlight/SpotlightIntegration.java +++ b/sentry-spotlight/src/main/java/io/sentry/spotlight/SpotlightIntegration.java @@ -16,6 +16,7 @@ import io.sentry.SentryExecutorService; import io.sentry.SentryIntegrationPackageStorage; import io.sentry.SentryOptions; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Platform; import java.io.Closeable; import java.io.IOException; @@ -81,6 +82,9 @@ private void sendEnvelope(final @NotNull SentryEnvelope envelope) { final GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { options.getSerializer().serialize(envelope, gzip); } catch (Throwable e) { + // Serializing reads the app's own data, such as attachments and serializable extras, so + // we can't know what it throws. The envelope is not sent to Spotlight. + ExceptionUtils.rethrowIfFatal(e); logger.log( ERROR, "An exception occurred while submitting the envelope to the Sentry server.", e); } finally { 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..b5e6785c92e 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,9 @@ 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. Only the default session cookie names are filtered then. + ExceptionUtils.rethrowIfFatal(t); scopes .getOptions() .getLogger() diff --git a/sentry-spring-7/src/main/java/io/sentry/spring7/SentrySpringFilter.java b/sentry-spring-7/src/main/java/io/sentry/spring7/SentrySpringFilter.java index 6abb989637e..3a452530a7d 100644 --- a/sentry-spring-7/src/main/java/io/sentry/spring7/SentrySpringFilter.java +++ b/sentry-spring-7/src/main/java/io/sentry/spring7/SentrySpringFilter.java @@ -17,6 +17,7 @@ import io.sentry.internal.eventprocessor.SentryEventProcessor; import io.sentry.spring7.tracing.SpringMvcTransactionNameProvider; import io.sentry.spring7.tracing.TransactionNameProvider; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Objects; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; @@ -101,6 +102,9 @@ private void configureScope( } }); } catch (Throwable e) { + // This runs inside the app's HTTP request and reads the container's request object, so we + // can't know what it throws. The request continues without Sentry request data on the scope. + ExceptionUtils.rethrowIfFatal(e); 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..0f2e5230138 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,9 @@ 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. + 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-7/src/main/java/io/sentry/spring7/kafka/SentryKafkaRecordInterceptor.java b/sentry-spring-7/src/main/java/io/sentry/spring7/kafka/SentryKafkaRecordInterceptor.java index abae5b44cb6..d5d511d6cf8 100644 --- a/sentry-spring-7/src/main/java/io/sentry/spring7/kafka/SentryKafkaRecordInterceptor.java +++ b/sentry-spring-7/src/main/java/io/sentry/spring7/kafka/SentryKafkaRecordInterceptor.java @@ -12,6 +12,7 @@ import io.sentry.TransactionContext; import io.sentry.TransactionOptions; import io.sentry.kafka.SentryKafkaProducer; +import io.sentry.util.ExceptionUtils; import io.sentry.util.SpanUtils; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; @@ -71,6 +72,9 @@ public SentryKafkaRecordInterceptor( startTransaction(forkedScopes, record, transactionContext); currentContext.set(new SentryRecordContext(lifecycleToken, transaction)); } catch (Throwable t) { + // This parses headers written by whichever producer sent the record, and tracing must never + // stop the record from reaching the listener. The record is processed without a transaction. + ExceptionUtils.rethrowIfFatal(t); scopes.getOptions().getLogger().log(SentryLevel.ERROR, "Unable to wrap Kafka consumer.", t); } return delegateIntercept(record, consumer); 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..d97946ce7a5 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,9 @@ 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. Only the default session cookie names are filtered then. + ExceptionUtils.rethrowIfFatal(t); scopes .getOptions() .getLogger() diff --git a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/SentrySpringFilter.java b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/SentrySpringFilter.java index a710116896c..02a98881718 100644 --- a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/SentrySpringFilter.java +++ b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/SentrySpringFilter.java @@ -17,6 +17,7 @@ import io.sentry.internal.eventprocessor.SentryEventProcessor; import io.sentry.spring.jakarta.tracing.SpringMvcTransactionNameProvider; import io.sentry.spring.jakarta.tracing.TransactionNameProvider; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Objects; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; @@ -101,6 +102,9 @@ private void configureScope( } }); } catch (Throwable e) { + // This runs inside the app's HTTP request and reads the container's request object, so we + // can't know what it throws. The request continues without Sentry request data on the scope. + ExceptionUtils.rethrowIfFatal(e); 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..754eea6bdde 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,9 @@ 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. + 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/kafka/SentryKafkaRecordInterceptor.java b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/kafka/SentryKafkaRecordInterceptor.java index 32db2eea846..511b719b616 100644 --- a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/kafka/SentryKafkaRecordInterceptor.java +++ b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/kafka/SentryKafkaRecordInterceptor.java @@ -12,6 +12,7 @@ import io.sentry.TransactionContext; import io.sentry.TransactionOptions; import io.sentry.kafka.SentryKafkaProducer; +import io.sentry.util.ExceptionUtils; import io.sentry.util.SpanUtils; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; @@ -71,6 +72,9 @@ public SentryKafkaRecordInterceptor( startTransaction(forkedScopes, record, transactionContext); currentContext.set(new SentryRecordContext(lifecycleToken, transaction)); } catch (Throwable t) { + // This parses headers written by whichever producer sent the record, and tracing must never + // stop the record from reaching the listener. The record is processed without a transaction. + ExceptionUtils.rethrowIfFatal(t); scopes.getOptions().getLogger().log(SentryLevel.ERROR, "Unable to wrap Kafka consumer.", t); } return delegateIntercept(record, consumer); 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..f598a58d7bb 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,9 @@ 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. Only the default session cookie names are filtered then. + ExceptionUtils.rethrowIfFatal(t); scopes .getOptions() .getLogger() diff --git a/sentry-spring/src/main/java/io/sentry/spring/SentrySpringFilter.java b/sentry-spring/src/main/java/io/sentry/spring/SentrySpringFilter.java index 4718ee982b1..353aecd8b4c 100644 --- a/sentry-spring/src/main/java/io/sentry/spring/SentrySpringFilter.java +++ b/sentry-spring/src/main/java/io/sentry/spring/SentrySpringFilter.java @@ -17,6 +17,7 @@ import io.sentry.internal.eventprocessor.SentryEventProcessor; import io.sentry.spring.tracing.SpringMvcTransactionNameProvider; import io.sentry.spring.tracing.TransactionNameProvider; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Objects; import java.io.IOException; import javax.servlet.FilterChain; @@ -101,6 +102,9 @@ private void configureScope( } }); } catch (Throwable e) { + // This runs inside the app's HTTP request and reads the container's request object, so we + // can't know what it throws. The request continues without Sentry request data on the scope. + ExceptionUtils.rethrowIfFatal(e); 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..1c44d0bdef8 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,9 @@ 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. + 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-spring/src/main/java/io/sentry/spring/kafka/SentryKafkaRecordInterceptor.java b/sentry-spring/src/main/java/io/sentry/spring/kafka/SentryKafkaRecordInterceptor.java index bf65b64f950..fadc3b3e1c0 100644 --- a/sentry-spring/src/main/java/io/sentry/spring/kafka/SentryKafkaRecordInterceptor.java +++ b/sentry-spring/src/main/java/io/sentry/spring/kafka/SentryKafkaRecordInterceptor.java @@ -12,6 +12,7 @@ import io.sentry.TransactionContext; import io.sentry.TransactionOptions; import io.sentry.kafka.SentryKafkaProducer; +import io.sentry.util.ExceptionUtils; import io.sentry.util.SpanUtils; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; @@ -77,6 +78,9 @@ public SentryKafkaRecordInterceptor( startTransaction(forkedScopes, record, transactionContext); currentContext.set(new SentryRecordContext(lifecycleToken, transaction)); } catch (Throwable t) { + // This parses headers written by whichever producer sent the record, and tracing must never + // stop the record from reaching the listener. The record is processed without a transaction. + ExceptionUtils.rethrowIfFatal(t); scopes.getOptions().getLogger().log(SentryLevel.ERROR, "Unable to wrap Kafka consumer.", t); } return delegateIntercept(record, consumer); diff --git a/sentry/src/main/java/io/sentry/DirectoryProcessor.java b/sentry/src/main/java/io/sentry/DirectoryProcessor.java index d9f0f32c40c..2870fb4b35e 100644 --- a/sentry/src/main/java/io/sentry/DirectoryProcessor.java +++ b/sentry/src/main/java/io/sentry/DirectoryProcessor.java @@ -8,6 +8,7 @@ import io.sentry.hints.Retryable; import io.sentry.hints.SubmissionResult; import io.sentry.transport.RateLimiter; +import io.sentry.util.ExceptionUtils; import io.sentry.util.HintUtils; import java.io.File; import java.util.Queue; @@ -101,6 +102,10 @@ public void processDirectory(final @NotNull File directory) { "Thread interrupted during processing '%s'", directory.getAbsolutePath()); } catch (Throwable e) { + // Processing a file deserializes data written by an earlier launch, another process or a + // hybrid SDK and captures it, so we can't know what it throws. The remaining files are left + // for the next run. + ExceptionUtils.rethrowIfFatal(e); logger.log(SentryLevel.ERROR, e, "Failed processing '%s'", directory.getAbsolutePath()); } } diff --git a/sentry/src/main/java/io/sentry/EnvelopeSender.java b/sentry/src/main/java/io/sentry/EnvelopeSender.java index 0aed2d62614..1a77a6ed070 100644 --- a/sentry/src/main/java/io/sentry/EnvelopeSender.java +++ b/sentry/src/main/java/io/sentry/EnvelopeSender.java @@ -3,6 +3,7 @@ import io.sentry.cache.EnvelopeCache; import io.sentry.hints.Flushable; import io.sentry.hints.Retryable; +import io.sentry.util.ExceptionUtils; import io.sentry.util.HintUtils; import io.sentry.util.Objects; import java.io.BufferedInputStream; @@ -77,6 +78,9 @@ protected void processFile(final @NotNull File file, final @NotNull Hint hint) { } catch (IOException e) { logger.log(SentryLevel.ERROR, e, "I/O on file '%s' failed.", file.getAbsolutePath()); } catch (Throwable e) { + // The cached file may be corrupt or come from an older SDK version, so we can't know what + // deserializing and capturing it throws. The file is deleted instead of retried. + ExceptionUtils.rethrowIfFatal(e); logger.log( SentryLevel.ERROR, e, "Failed to capture cached envelope %s", file.getAbsolutePath()); HintUtils.runIfHasTypeLogIfNot( 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/JsonSerializer.java b/sentry/src/main/java/io/sentry/JsonSerializer.java index d8b02c1a1c3..cf94708eba0 100644 --- a/sentry/src/main/java/io/sentry/JsonSerializer.java +++ b/sentry/src/main/java/io/sentry/JsonSerializer.java @@ -37,6 +37,7 @@ import io.sentry.rrweb.RRWebMetaEvent; import io.sentry.rrweb.RRWebSpanEvent; import io.sentry.rrweb.RRWebVideoEvent; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Objects; import java.io.BufferedOutputStream; import java.io.BufferedWriter; @@ -168,6 +169,9 @@ public JsonSerializer(@NotNull SentryOptions options) { return (T) jsonObjectReader.nextObjectOrNull(); } } catch (Throwable e) { + // The JSON may be corrupt and the element deserializer is supplied by the caller, so we + // can't know what this throws. The collection is treated as absent. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, "Error when deserializing", e); return null; } diff --git a/sentry/src/main/java/io/sentry/OutboxSender.java b/sentry/src/main/java/io/sentry/OutboxSender.java index 21952dc0c5a..2f25a0a8f37 100644 --- a/sentry/src/main/java/io/sentry/OutboxSender.java +++ b/sentry/src/main/java/io/sentry/OutboxSender.java @@ -12,6 +12,7 @@ import io.sentry.protocol.SentryId; import io.sentry.protocol.SentryTransaction; import io.sentry.util.CollectionUtils; +import io.sentry.util.ExceptionUtils; import io.sentry.util.HintUtils; import io.sentry.util.LogUtils; import io.sentry.util.Objects; @@ -153,6 +154,9 @@ private void processEnvelope(final @NotNull SentryEnvelope envelope, final @NotN } } } catch (Throwable e) { + // Outbox items are written by other processes, such as the native SDK or a hybrid SDK, + // so we can't know what deserializing and capturing them throws. The item is skipped. + ExceptionUtils.rethrowIfFatal(e); logger.log(ERROR, "Item failed to process.", e); } } else if (SentryItemType.Transaction.equals(item.getHeader().getType())) { @@ -190,6 +194,9 @@ private void processEnvelope(final @NotNull SentryEnvelope envelope, final @NotN } } } catch (Throwable e) { + // Outbox items are written by other processes, such as the native SDK or a hybrid SDK, + // so we can't know what deserializing and capturing them throws. The item is skipped. + ExceptionUtils.rethrowIfFatal(e); logger.log(ERROR, "Item failed to process.", e); } } else { diff --git a/sentry/src/main/java/io/sentry/PreviousSessionFinalizer.java b/sentry/src/main/java/io/sentry/PreviousSessionFinalizer.java index 4e3b2e9b3d2..93307889816 100644 --- a/sentry/src/main/java/io/sentry/PreviousSessionFinalizer.java +++ b/sentry/src/main/java/io/sentry/PreviousSessionFinalizer.java @@ -8,6 +8,7 @@ import io.sentry.cache.EnvelopeCache; import io.sentry.cache.IEnvelopeCache; +import io.sentry.util.ExceptionUtils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; @@ -127,6 +128,10 @@ public void run() { scopes.captureEnvelope(fromSession); } } catch (Throwable e) { + // The session file was written by an earlier launch and may be corrupt, so we can't know + // what deserializing it throws. The previous session is not sent, and its file is still + // deleted below. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, "Error processing previous session.", e); } diff --git a/sentry/src/main/java/io/sentry/ProfilingTraceData.java b/sentry/src/main/java/io/sentry/ProfilingTraceData.java index aee42fa07d4..7e126ec6de8 100644 --- a/sentry/src/main/java/io/sentry/ProfilingTraceData.java +++ b/sentry/src/main/java/io/sentry/ProfilingTraceData.java @@ -1,6 +1,7 @@ package io.sentry; import io.sentry.profilemeasurements.ProfileMeasurement; +import io.sentry.util.ExceptionUtils; import io.sentry.vendor.gson.stream.JsonToken; import java.io.File; import java.io.IOException; @@ -365,8 +366,10 @@ public void setSampledProfile(final @Nullable String sampledProfile) { public void readDeviceCpuFrequencies() { try { this.deviceCpuFrequencies = deviceCpuFrequenciesReader.call(); - } catch (Throwable ignored) { - // should never happen + } catch (Throwable t) { + // The reader is supplied by the platform integration and declares any Exception, so we + // can't know what it throws. The profile is sent without CPU frequencies. + ExceptionUtils.rethrowIfFatal(t); } } diff --git a/sentry/src/main/java/io/sentry/Scope.java b/sentry/src/main/java/io/sentry/Scope.java index b05e4d9d05c..e07156b8625 100644 --- a/sentry/src/main/java/io/sentry/Scope.java +++ b/sentry/src/main/java/io/sentry/Scope.java @@ -496,6 +496,9 @@ 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. As the spec asks, the breadcrumb is + // dropped. + 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 75c263c4127..1293172023a 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; @@ -164,6 +165,9 @@ public boolean isEnabled() { sentryId = getClient().captureEvent(event, localScope, hint); updateLastEventId(sentryId); } catch (Throwable e) { + // A public API entry point: capturing runs integration and app code, such as event + // processors, so we can't know what it throws. The event is dropped. + ExceptionUtils.rethrowIfFatal(e); getOptions() .getLogger() .log( @@ -192,6 +196,9 @@ 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. The event is captured with the + // unchanged scope. + ExceptionUtils.rethrowIfFatal(t); getOptions() .getLogger() .log(SentryLevel.ERROR, "Error in the 'ScopeCallback' callback.", t); @@ -235,6 +242,9 @@ private void assignTraceContext(final @NotNull SentryEvent event) { sentryId = getClient().captureMessage(message, level, localScope); } catch (Throwable e) { + // A public API entry point: capturing runs integration and app code, such as event + // processors, so we can't know what it throws. The message is dropped. + ExceptionUtils.rethrowIfFatal(e); getOptions() .getLogger() .log(SentryLevel.ERROR, "Error while capturing message: " + message, e); @@ -266,6 +276,9 @@ private void assignTraceContext(final @NotNull SentryEvent event) { sentryId = getClient().captureFeedback(feedback, hint, localScope); } catch (Throwable e) { + // A public API entry point: capturing runs integration and app code, such as event + // processors, so we can't know what it throws. The feedback is dropped. + ExceptionUtils.rethrowIfFatal(e); getOptions() .getLogger() .log(SentryLevel.ERROR, "Error while capturing feedback: " + feedback.getMessage(), e); @@ -294,6 +307,9 @@ private void assignTraceContext(final @NotNull SentryEvent event) { sentryId = capturedEnvelopeId; } } catch (Throwable e) { + // An entry point for hybrid SDKs and cached envelopes, whose items may run their own data + // factories, so we can't know what it throws. The envelope is dropped. + ExceptionUtils.rethrowIfFatal(e); getOptions().getLogger().log(SentryLevel.ERROR, "Error while capturing envelope.", e); } } @@ -339,6 +355,9 @@ private void assignTraceContext(final @NotNull SentryEvent event) { sentryId = getClient().captureEvent(event, localScope, hint); } catch (Throwable e) { + // A public API entry point: capturing runs integration and app code, such as event + // processors, so we can't know what it throws. The exception is not reported. + ExceptionUtils.rethrowIfFatal(e); getOptions() .getLogger() .log( @@ -429,6 +448,9 @@ public void close(final boolean isRestarting) { try { ((Closeable) eventProcessor).close(); } 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( @@ -670,6 +692,8 @@ 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. The rest of the callback is skipped. + ExceptionUtils.rethrowIfFatal(e); getOptions().getLogger().log(SentryLevel.ERROR, "Error in the 'withScope' callback.", e); } @@ -678,6 +702,8 @@ 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. The rest of the callback is skipped. + ExceptionUtils.rethrowIfFatal(e); getOptions().getLogger().log(SentryLevel.ERROR, "Error in the 'withScope' callback.", e); } } @@ -689,6 +715,8 @@ 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. The rest of the callback is skipped. + ExceptionUtils.rethrowIfFatal(e); getOptions() .getLogger() .log(SentryLevel.ERROR, "Error in the 'withIsolationScope' callback.", e); @@ -699,6 +727,8 @@ 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. The rest of the callback is skipped. + ExceptionUtils.rethrowIfFatal(e); getOptions() .getLogger() .log(SentryLevel.ERROR, "Error in the 'withIsolationScope' callback.", e); @@ -719,6 +749,8 @@ public void configureScope( try { callback.run(combinedScope.getSpecificScope(scopeType)); } catch (Throwable e) { + // A user callback, so we can't know what it throws. The rest of the callback is skipped. + ExceptionUtils.rethrowIfFatal(e); getOptions() .getLogger() .log(SentryLevel.ERROR, "Error in the 'configureScope' callback.", e); @@ -752,6 +784,9 @@ public void flush(long timeoutMillis) { try { getClient().flush(timeoutMillis); } catch (Throwable e) { + // A public API entry point: flushing runs the transport, which integrations and the app can + // replace, so we can't know what it throws. Whatever was not flushed stays queued. + ExceptionUtils.rethrowIfFatal(e); getOptions().getLogger().log(SentryLevel.ERROR, "Error in the 'client.flush'.", e); } } @@ -821,6 +856,10 @@ public void flush(long timeoutMillis) { hint, profilingTraceData); } catch (Throwable e) { + // An entry point that finishing a transaction calls on the app's thread: capturing + // runs integration and app code, such as event processors, so we can't know what it + // throws. The transaction is dropped. + ExceptionUtils.rethrowIfFatal(e); getOptions() .getLogger() .log( @@ -851,6 +890,10 @@ public void flush(long timeoutMillis) { try { sentryId = getClient().captureProfileChunk(profilingContinuousData, getCombinedScopeView()); } catch (Throwable e) { + // Capturing reads and converts the profiler's trace file, possibly with a third-party + // converter, and runs event processors, so we can't know what it throws. The chunk is + // dropped. + ExceptionUtils.rethrowIfFatal(e); getOptions() .getLogger() .log( @@ -1145,6 +1188,9 @@ public void reportFullyDisplayed() { try { sentryId = getClient().captureCheckIn(checkIn, getCombinedScopeView(), null); } catch (Throwable e) { + // A public API entry point: capturing runs integration and app code, such as the + // transport, so we can't know what it throws. The check-in is dropped. + ExceptionUtils.rethrowIfFatal(e); getOptions() .getLogger() .log(SentryLevel.ERROR, "Error while capturing check-in for slug", e); @@ -1168,6 +1214,9 @@ public void reportFullyDisplayed() { try { sentryId = getClient().captureReplayEvent(replay, getCombinedScopeView(), hint); } catch (Throwable e) { + // Capturing runs integration and app code, such as event processors, so we can't know + // what it throws. The replay segment is dropped. + ExceptionUtils.rethrowIfFatal(e); getOptions().getLogger().log(SentryLevel.ERROR, "Error while capturing replay", e); } } diff --git a/sentry/src/main/java/io/sentry/SendCachedEnvelopeFireAndForgetIntegration.java b/sentry/src/main/java/io/sentry/SendCachedEnvelopeFireAndForgetIntegration.java index a9a8c1d8fe2..3ef1161a2ac 100644 --- a/sentry/src/main/java/io/sentry/SendCachedEnvelopeFireAndForgetIntegration.java +++ b/sentry/src/main/java/io/sentry/SendCachedEnvelopeFireAndForgetIntegration.java @@ -4,6 +4,7 @@ import io.sentry.transport.RateLimiter; import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Objects; import java.io.Closeable; import java.io.File; @@ -158,6 +159,10 @@ private void sendCachedEnvelopes( sender.send(); } catch (Throwable e) { + // The sender comes from a factory that integrations and the app can provide, and it + // deserializes and captures cached files, so we can't know what it throws. The + // cached events stay on disk for the next attempt. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, "Failed trying to send cached events.", e); } }); diff --git a/sentry/src/main/java/io/sentry/Sentry.java b/sentry/src/main/java/io/sentry/Sentry.java index ce286600477..76a07dd04bb 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; @@ -253,6 +254,9 @@ private static void applyOptionsConfiguration( try { optionsConfiguration.configure(options); } catch (Throwable t) { + // A user callback, so we can't know what it throws. The SDK is initialized with the options + // the callback set before it threw. + ExceptionUtils.rethrowIfFatal(t); options .getLogger() .log(SentryLevel.ERROR, "Error in the 'OptionsConfiguration.configure' callback.", t); @@ -1032,6 +1036,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) { @@ -1045,6 +1055,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) { @@ -1054,6 +1070,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) { @@ -1063,6 +1084,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( @@ -1266,6 +1292,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 b5027432625..6853ccf556f 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; @@ -229,6 +230,9 @@ 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. As the spec asks, the replay is not + // captured for this error. + ExceptionUtils.rethrowIfFatal(e); options .getLogger() .log( @@ -953,6 +957,9 @@ 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. The + // envelope is still sent. + ExceptionUtils.rethrowIfFatal(e); options .getLogger() .log(SentryLevel.ERROR, "The BeforeEnvelope callback threw an exception.", e); @@ -1641,6 +1648,9 @@ 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. As the spec asks, the event is + // dropped. + ExceptionUtils.rethrowIfFatal(e); options .getLogger() .log( @@ -1670,6 +1680,9 @@ 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. As the spec asks, the transaction is + // dropped. + ExceptionUtils.rethrowIfFatal(e); options .getLogger() .log( @@ -1730,6 +1743,9 @@ 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. As the spec asks, the feedback is + // dropped. + ExceptionUtils.rethrowIfFatal(e); options .getLogger() .log( @@ -1757,6 +1773,9 @@ 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. As the spec asks, the replay segment + // is dropped. + ExceptionUtils.rethrowIfFatal(e); options .getLogger() .log( @@ -1785,6 +1804,8 @@ 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. As the spec asks, the log is dropped. + ExceptionUtils.rethrowIfFatal(e); options .getLogger() .log( @@ -1810,6 +1831,9 @@ 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. As the spec asks, the metric is + // dropped. + ExceptionUtils.rethrowIfFatal(e); options .getLogger() .log( diff --git a/sentry/src/main/java/io/sentry/SentryEnvelopeItem.java b/sentry/src/main/java/io/sentry/SentryEnvelopeItem.java index 2873d2c8ad4..b635c9fbd5e 100644 --- a/sentry/src/main/java/io/sentry/SentryEnvelopeItem.java +++ b/sentry/src/main/java/io/sentry/SentryEnvelopeItem.java @@ -8,6 +8,7 @@ import io.sentry.exception.SentryEnvelopeException; import io.sentry.protocol.SentryTransaction; import io.sentry.protocol.profiling.SentryProfile; +import io.sentry.util.ExceptionUtils; import io.sentry.util.FileUtils; import io.sentry.util.JsonSerializationUtils; import io.sentry.util.Objects; @@ -550,6 +551,10 @@ public static SentryEnvelopeItem fromReplay( return serializeToMsgpack(replayPayload); } } catch (Throwable t) { + // The recording holds data from integrations and the app, such as breadcrumb data and + // network details, that is serialized reflectively, so we can't know what this throws. + // The item is sent with an empty payload, so the replay segment is lost. + ExceptionUtils.rethrowIfFatal(t); logger.log(SentryLevel.ERROR, "Could not serialize replay recording", t); return null; } finally { diff --git a/sentry/src/main/java/io/sentry/SentryEnvelopeItemHeader.java b/sentry/src/main/java/io/sentry/SentryEnvelopeItemHeader.java index eaacee9957a..54c5b2aa127 100644 --- a/sentry/src/main/java/io/sentry/SentryEnvelopeItemHeader.java +++ b/sentry/src/main/java/io/sentry/SentryEnvelopeItemHeader.java @@ -1,5 +1,6 @@ package io.sentry; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Objects; import io.sentry.vendor.gson.stream.JsonToken; import java.io.IOException; @@ -33,8 +34,11 @@ public int getLength() { if (getLength != null) { try { return getLength.call(); - } catch (Throwable ignored) { + } catch (Throwable t) { + // The length comes from the item's data factory, which serializes data from integrations + // and the app, so we can't know what it throws. The header reports an unknown length. // TODO: Take ILogger via ctor or hook into internal static logger + ExceptionUtils.rethrowIfFatal(t); return -1; } } diff --git a/sentry/src/main/java/io/sentry/SentryOptions.java b/sentry/src/main/java/io/sentry/SentryOptions.java index 5ba97164a5e..67bd94146b8 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..d1779f9324c 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,8 @@ 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. The transaction is not profiled. + ExceptionUtils.rethrowIfFatal(t); profilesSamplerFailed = true; options .getLogger() @@ -47,6 +50,9 @@ 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. As the spec asks, the transaction is + // dropped. + ExceptionUtils.rethrowIfFatal(t); options .getLogger() .log(SentryLevel.ERROR, "Error in the 'TracesSamplerCallback' callback.", t); diff --git a/sentry/src/main/java/io/sentry/UncaughtExceptionHandlerIntegration.java b/sentry/src/main/java/io/sentry/UncaughtExceptionHandlerIntegration.java index 07e9b6357d7..6be630a0c7a 100644 --- a/sentry/src/main/java/io/sentry/UncaughtExceptionHandlerIntegration.java +++ b/sentry/src/main/java/io/sentry/UncaughtExceptionHandlerIntegration.java @@ -144,6 +144,9 @@ public void uncaughtException(Thread thread, Throwable thrown) { } } } catch (Throwable e) { + // Deliberately broad and without ExceptionUtils.rethrowIfFatal: this thread is already + // dying, and rethrowing would skip the chained handler below, which is what makes the app + // crash as it normally would (on Android, it kills the process). The crash event is lost. options .getLogger() .log(SentryLevel.ERROR, "Error sending uncaught exception to Sentry.", e); diff --git a/sentry/src/main/java/io/sentry/cache/CacheStrategy.java b/sentry/src/main/java/io/sentry/cache/CacheStrategy.java index 5f3e605f2a1..9747fff1a28 100644 --- a/sentry/src/main/java/io/sentry/cache/CacheStrategy.java +++ b/sentry/src/main/java/io/sentry/cache/CacheStrategy.java @@ -10,6 +10,7 @@ import io.sentry.SentryOptions; import io.sentry.Session; import io.sentry.clientreport.DiscardReason; +import io.sentry.util.ExceptionUtils; import io.sentry.util.LazyDirectory; import io.sentry.util.LazyEvaluator; import io.sentry.util.Objects; @@ -258,6 +259,9 @@ private boolean isSessionType(final @Nullable SentryEnvelopeItem item) { new InputStreamReader(new ByteArrayInputStream(item.getData()), UTF_8))) { return serializer.getValue().deserialize(reader, Session.class); } catch (Throwable e) { + // getData() runs the item's data factory and the cached payload may be corrupt, so we can't + // know what this throws. The item is treated as if it had no session. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(ERROR, "Failed to deserialize the session.", e); } return null; @@ -270,6 +274,9 @@ private void saveNewEnvelope( // we need to set the same timestamp so the sorting from oldest to newest wont break. file.setLastModified(timestamp); } catch (Throwable e) { + // Serializing the envelope runs its items' data factories, e.g. an attachment's byte + // provider, so we can't know what this throws. The cached file may be left incomplete. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(ERROR, "Failed to serialize the new envelope to the disk.", e); } } diff --git a/sentry/src/main/java/io/sentry/cache/CacheUtils.java b/sentry/src/main/java/io/sentry/cache/CacheUtils.java index 142b7c3fdab..b53c833ff8d 100644 --- a/sentry/src/main/java/io/sentry/cache/CacheUtils.java +++ b/sentry/src/main/java/io/sentry/cache/CacheUtils.java @@ -7,6 +7,7 @@ import io.sentry.JsonDeserializer; import io.sentry.SentryLevel; import io.sentry.SentryOptions; +import io.sentry.util.ExceptionUtils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; @@ -46,6 +47,9 @@ public static void store( final Writer writer = new BufferedWriter(new OutputStreamWriter(outputStream, UTF_8))) { options.getSerializer().serialize(entity, writer); } catch (Throwable e) { + // Scope values can hold arbitrary app objects that are serialized reflectively, so we can't + // know what this throws. The value is not persisted for the next launch. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(ERROR, e, "Error persisting entity: %s", fileName); } } @@ -89,6 +93,9 @@ static void delete( return options.getSerializer().deserializeCollection(reader, clazz, elementDeserializer); } } catch (Throwable e) { + // The file was written by an earlier launch, possibly an older SDK version, and may be + // corrupt, so we can't know what deserializing it throws. The value is treated as absent. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(ERROR, e, "Error reading entity from scope cache: %s", fileName); } } else { diff --git a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java index 3fde2a97f5a..870b5c9d9c1 100644 --- a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java +++ b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java @@ -25,6 +25,7 @@ import io.sentry.hints.SessionStart; import io.sentry.transport.NoOpEnvelopeCache; import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.util.ExceptionUtils; import io.sentry.util.HintUtils; import io.sentry.util.Objects; import java.io.BufferedInputStream; @@ -262,6 +263,10 @@ private void tryEndPreviousSession(final @NotNull Hint hint) { writeSessionToDisk(previousSessionFile, session); } } catch (Throwable e) { + // The session file was written by an earlier launch and may be corrupt, and the exit hint + // comes from another integration, so we can't know what this throws. The previous session + // is left as it is on disk. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, "Error processing previous session.", e); } } else { @@ -303,6 +308,9 @@ private void writeCrashMarkerFile() { return session; } } catch (Throwable e) { + // getData() runs the item's data factory, so we can't know what this throws. The + // envelope is treated as if it had no session. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(ERROR, "Item failed to process.", e); } } else { @@ -350,6 +358,9 @@ private boolean writeEnvelopeToDisk( try (final OutputStream outputStream = new FileOutputStream(file)) { serializer.getValue().serialize(envelope, outputStream); } catch (Throwable e) { + // Serializing the envelope runs its items' data factories, e.g. an attachment's byte + // provider, so we can't know what this throws. The envelope is not cached. + ExceptionUtils.rethrowIfFatal(e); options .getLogger() .log(ERROR, e, "Error writing Envelope %s to offline storage", file.getAbsolutePath()); diff --git a/sentry/src/main/java/io/sentry/cache/PersistingScopeObserver.java b/sentry/src/main/java/io/sentry/cache/PersistingScopeObserver.java index cf3bfcb3d15..9337138a30f 100644 --- a/sentry/src/main/java/io/sentry/cache/PersistingScopeObserver.java +++ b/sentry/src/main/java/io/sentry/cache/PersistingScopeObserver.java @@ -16,6 +16,7 @@ import io.sentry.protocol.Request; import io.sentry.protocol.SentryId; import io.sentry.protocol.User; +import io.sentry.util.ExceptionUtils; import io.sentry.util.LazyEvaluator; import java.io.BufferedReader; import java.io.BufferedWriter; @@ -110,6 +111,9 @@ public Breadcrumb from(byte[] source) { new InputStreamReader(new ByteArrayInputStream(source), UTF_8))) { return options.getSerializer().deserialize(reader, Breadcrumb.class); } catch (Throwable e) { + // The queue file was written by an earlier launch and may be corrupt, so we + // can't know what deserializing it throws. The breadcrumb is skipped. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(ERROR, e, "Error reading entity from scope cache"); } return null; @@ -324,6 +328,9 @@ private void runSafely(final @NotNull Runnable task) { try { task.run(); } catch (Throwable e) { + // The task serializes scope values, which can hold arbitrary app objects, so we can't know + // what it throws. The changes it had not written yet are not persisted. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(ERROR, "Serialization task failed", e); } } diff --git a/sentry/src/main/java/io/sentry/clientreport/ClientReportRecorder.java b/sentry/src/main/java/io/sentry/clientreport/ClientReportRecorder.java index ba6d60e2563..e8e49039173 100644 --- a/sentry/src/main/java/io/sentry/clientreport/ClientReportRecorder.java +++ b/sentry/src/main/java/io/sentry/clientreport/ClientReportRecorder.java @@ -9,6 +9,8 @@ import io.sentry.SentryOptions; import io.sentry.protocol.SentrySpan; import io.sentry.protocol.SentryTransaction; +import io.sentry.util.ExceptionUtils; +import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -46,7 +48,7 @@ public ClientReportRecorder(@NotNull SentryOptions options) { items.add(SentryEnvelopeItem.fromClientReport(options.getSerializer(), clientReport)); return new SentryEnvelope(envelope.getHeader(), items); - } catch (Throwable e) { + } catch (IOException e) { options.getLogger().log(SentryLevel.ERROR, e, "Unable to attach client report to envelope."); return envelope; } @@ -125,6 +127,9 @@ public void recordLostEnvelopeItem( } } } catch (Throwable e) { + // getData() runs the item's data factory, which may also deserialize a dropped transaction, + // so we can't know what this throws. The lost item may not be counted in the client report. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, e, "Unable to record lost envelope item."); } } @@ -151,6 +156,9 @@ private void executeOnDiscard( try { options.getOnDiscard().execute(reason, category, countToAdd); } catch (Throwable e) { + // A user callback, so we can't know what it throws. Only this notification is lost; the + // discard is still counted in the client report. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, "The onDiscard callback threw an exception.", e); } } diff --git a/sentry/src/main/java/io/sentry/logger/LoggerApi.java b/sentry/src/main/java/io/sentry/logger/LoggerApi.java index 1933d7f0fe3..a5a6e4a89c3 100644 --- a/sentry/src/main/java/io/sentry/logger/LoggerApi.java +++ b/sentry/src/main/java/io/sentry/logger/LoggerApi.java @@ -17,6 +17,7 @@ import io.sentry.protocol.SdkVersion; import io.sentry.protocol.SentryId; import io.sentry.protocol.User; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Platform; import io.sentry.util.TracingUtils; import java.util.HashMap; @@ -130,6 +131,9 @@ private void captureLog( scopes.getClient().captureLog(logEvent, combinedScope); } catch (Throwable e) { + // A public API entry point whose capture runs integration and app code, such as event + // processors, so we can't know what it throws. The log is dropped. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, "Error while capturing log event", e); } } @@ -143,6 +147,10 @@ private void captureLog( try { return String.format(message, args); } catch (Throwable t) { + // Formatting calls the app's toString() and Formattable implementations of the arguments, + // and the format string may not match them, so we can't know what this throws. The log is + // sent with the unformatted message. + ExceptionUtils.rethrowIfFatal(t); scopes .getOptions() .getLogger() diff --git a/sentry/src/main/java/io/sentry/metrics/MetricsApi.java b/sentry/src/main/java/io/sentry/metrics/MetricsApi.java index 9648b99d37f..a92e431821f 100644 --- a/sentry/src/main/java/io/sentry/metrics/MetricsApi.java +++ b/sentry/src/main/java/io/sentry/metrics/MetricsApi.java @@ -16,6 +16,7 @@ import io.sentry.protocol.SdkVersion; import io.sentry.protocol.SentryId; import io.sentry.protocol.User; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Platform; import io.sentry.util.TracingUtils; import java.util.HashMap; @@ -151,6 +152,9 @@ private void captureMetrics( scopes.getClient().captureMetric(metricsEvent, combinedScope, params.getHint()); } catch (Throwable e) { + // A public API entry point whose capture runs integration and app code, such as event + // processors, so we can't know what it throws. The metric is dropped. + ExceptionUtils.rethrowIfFatal(e); options.getLogger().log(SentryLevel.ERROR, "Error while capturing metrics event", e); } } diff --git a/sentry/src/main/java/io/sentry/transport/HttpConnection.java b/sentry/src/main/java/io/sentry/transport/HttpConnection.java index 34abeb31835..dbbf7fbbfef 100644 --- a/sentry/src/main/java/io/sentry/transport/HttpConnection.java +++ b/sentry/src/main/java/io/sentry/transport/HttpConnection.java @@ -7,6 +7,7 @@ import io.sentry.RequestDetails; import io.sentry.SentryEnvelope; import io.sentry.SentryOptions; +import io.sentry.util.ExceptionUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -157,6 +158,10 @@ HttpURLConnection open() throws IOException { final GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { options.getSerializer().serialize(envelope, gzip); } catch (Throwable e) { + // Besides network failures, serializing runs the items' data factories, e.g. an + // attachment's byte provider, so we can't know what this throws. The server's response to + // the incomplete request still decides the result. + ExceptionUtils.rethrowIfFatal(e); options .getLogger() .log( diff --git a/sentry/src/main/java/io/sentry/transport/StdoutTransport.java b/sentry/src/main/java/io/sentry/transport/StdoutTransport.java index c24f96dbffd..81a212a5cb4 100644 --- a/sentry/src/main/java/io/sentry/transport/StdoutTransport.java +++ b/sentry/src/main/java/io/sentry/transport/StdoutTransport.java @@ -3,6 +3,7 @@ import io.sentry.Hint; import io.sentry.ISerializer; import io.sentry.SentryEnvelope; +import io.sentry.util.ExceptionUtils; import io.sentry.util.Objects; import java.io.IOException; import org.jetbrains.annotations.NotNull; @@ -24,8 +25,10 @@ public void send(final @NotNull SentryEnvelope envelope, final @NotNull Hint hin try { serializer.serialize(envelope, System.out); } catch (Throwable e) { + // Serializing runs the items' data factories, e.g. an attachment's byte provider, so we + // can't know what this throws. The envelope may be printed only partially. // TODO: debug log so we be aware serialization failed here - // do nothing + ExceptionUtils.rethrowIfFatal(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..e8423fb720d 100644 --- a/sentry/src/main/java/io/sentry/util/EventSizeLimitingUtils.java +++ b/sentry/src/main/java/io/sentry/util/EventSizeLimitingUtils.java @@ -69,6 +69,9 @@ private EventSizeLimitingUtils() {} return reducedEvent; } } catch (Throwable e) { + // A user callback, so we can't know what it throws. Its result is ignored, and the + // automatic reduction continues with the original event. + ExceptionUtils.rethrowIfFatal(e); options .getLogger() .log( @@ -96,6 +99,9 @@ private EventSizeLimitingUtils() {} return reducedEvent; } catch (Throwable e) { + // Measuring the size serializes the event, which holds data from integrations and the app, + // reflectively, so we can't know what this throws. The event is sent as is. + ExceptionUtils.rethrowIfFatal(e); options .getLogger() .log( diff --git a/sentry/src/main/java/io/sentry/util/JsonSerializationUtils.java b/sentry/src/main/java/io/sentry/util/JsonSerializationUtils.java index e515ef6fd69..5b94543a585 100644 --- a/sentry/src/main/java/io/sentry/util/JsonSerializationUtils.java +++ b/sentry/src/main/java/io/sentry/util/JsonSerializationUtils.java @@ -61,6 +61,9 @@ public final class JsonSerializationUtils { return stream.toByteArray(); } } catch (Throwable t) { + // The serializable can hold data from integrations and the app that is serialized + // reflectively, so we can't know what this throws. The caller gets no bytes. + ExceptionUtils.rethrowIfFatal(t); logger.log(SentryLevel.ERROR, "Could not serialize serializable", t); return null; } @@ -88,6 +91,9 @@ public static long byteSizeOf( serializer.serialize(serializable, writer, false); return writer.getByteCount(); } catch (Throwable t) { + // The serializable can hold data from integrations and the app that is serialized + // reflectively, so we can't know what this throws. Its size is reported as 0. + ExceptionUtils.rethrowIfFatal(t); logger.log(SentryLevel.ERROR, "Could not calculate size of serializable", t); return 0; } diff --git a/sentry/src/test/java/io/sentry/ScopeTest.kt b/sentry/src/test/java/io/sentry/ScopeTest.kt index 536f869ebc8..ae3e67ffc45 100644 --- a/sentry/src/test/java/io/sentry/ScopeTest.kt +++ b/sentry/src/test/java/io/sentry/ScopeTest.kt @@ -10,6 +10,7 @@ import io.sentry.test.callMethod import java.util.concurrent.CopyOnWriteArrayList import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNotSame @@ -378,6 +379,17 @@ class ScopeTest { assertThat(scope.breadcrumbs.single().message).isEqualTo("kept") } + @Test + fun `when beforeBreadcrumb throws a fatal error, it propagates`() { + val options = + SentryOptions().apply { setBeforeBreadcrumb { _, _ -> throw OutOfMemoryError("test") } } + + val scope = Scope(options) + + assertFailsWith { scope.addBreadcrumb(Breadcrumb()) } + assertThat(scope.breadcrumbs).isEmpty() + } + @Test fun `when adding breadcrumb, executeBreadcrumb wont be executed as its not set, but it will be added`() { val options = SentryOptions() diff --git a/sentry/src/test/java/io/sentry/ScopesTest.kt b/sentry/src/test/java/io/sentry/ScopesTest.kt index 15e1d82941d..5ea0ed739aa 100644 --- a/sentry/src/test/java/io/sentry/ScopesTest.kt +++ b/sentry/src/test/java/io/sentry/ScopesTest.kt @@ -785,6 +785,35 @@ class ScopesTest { verify(logger).log(eq(SentryLevel.ERROR), any(), eq(exception)) } + @Test + fun `when captureException is called with a ScopeCallback that throws a fatal error, it propagates`() { + val (sut, mockClient) = getEnabledScopes() + + assertFailsWith { + sut.captureException(Throwable()) { throw OutOfMemoryError("scope callback") } + } + verify(mockClient, never()).captureEvent(any(), anyOrNull(), anyOrNull()) + } + + @Test + fun `when the client throws a fatal error while capturing, it propagates`() { + val (sut, mockClient) = getEnabledScopes() + whenever(mockClient.captureEvent(any(), anyOrNull(), anyOrNull())) + .thenThrow(OutOfMemoryError("client")) + + assertFailsWith { sut.captureException(Throwable()) } + } + + @Test + fun `when the client throws a runtime exception while capturing, it is logged`() { + val (sut, mockClient, logger) = getEnabledScopes() + val exception = IllegalStateException("client") + whenever(mockClient.captureEvent(any(), anyOrNull(), anyOrNull())).thenThrow(exception) + + assertThat(sut.captureException(Throwable())).isEqualTo(SentryId.EMPTY_ID) + verify(logger).log(eq(SentryLevel.ERROR), any(), eq(exception)) + } + // endregion // region captureCheckIn tests @@ -899,6 +928,31 @@ class ScopesTest { verify(logger).log(eq(SentryLevel.ERROR), any(), eq(exception)) } + @Test + fun `when withScope throws a runtime exception then it is swallowed`() { + val (scopes, _, logger) = getEnabledScopes() + val exception = IllegalStateException("scope callback exception") + + scopes.withScope { throw exception } + + verify(logger).log(eq(SentryLevel.ERROR), any(), eq(exception)) + } + + @Test + fun `when withScope throws a fatal error then it propagates`() { + val (scopes) = getEnabledScopes() + + assertFailsWith { scopes.withScope { throw OutOfMemoryError("callback") } } + } + + @Test + fun `when withScope on a closed scopes throws a fatal error then it propagates`() { + val (scopes) = getEnabledScopes() + scopes.close() + + assertFailsWith { scopes.withScope { throw OutOfMemoryError("callback") } } + } + // endregion // region withIsolationScope tests @@ -935,6 +989,35 @@ class ScopesTest { verify(logger).log(eq(SentryLevel.ERROR), any(), eq(exception)) } + @Test + fun `when withIsolationScope throws a runtime exception then it is swallowed`() { + val (scopes, _, logger) = getEnabledScopes() + val exception = IllegalStateException("scope callback exception") + + scopes.withIsolationScope { throw exception } + + verify(logger).log(eq(SentryLevel.ERROR), any(), eq(exception)) + } + + @Test + fun `when withIsolationScope throws a fatal error then it propagates`() { + val (scopes) = getEnabledScopes() + + assertFailsWith { + scopes.withIsolationScope { throw OutOfMemoryError("callback") } + } + } + + @Test + fun `when withIsolationScope on a closed scopes throws a fatal error then it propagates`() { + val (scopes) = getEnabledScopes() + scopes.close() + + assertFailsWith { + scopes.withIsolationScope { throw OutOfMemoryError("callback") } + } + } + // endregion // region configureScope tests @@ -971,6 +1054,25 @@ class ScopesTest { verify(logger).log(eq(SentryLevel.ERROR), any(), eq(exception)) } + @Test + fun `when configureScope throws a runtime exception then it is swallowed`() { + val (scopes, _, logger) = getEnabledScopes() + val exception = IllegalStateException("scope callback exception") + + scopes.configureScope { throw exception } + + verify(logger).log(eq(SentryLevel.ERROR), any(), eq(exception)) + } + + @Test + fun `when configureScope throws a fatal error then it propagates`() { + val (scopes) = getEnabledScopes() + + assertFailsWith { + scopes.configureScope { throw OutOfMemoryError("callback") } + } + } + // endregion @Test diff --git a/sentry/src/test/java/io/sentry/SentryClientTest.kt b/sentry/src/test/java/io/sentry/SentryClientTest.kt index c1e96f842b7..dd3acf2e274 100644 --- a/sentry/src/test/java/io/sentry/SentryClientTest.kt +++ b/sentry/src/test/java/io/sentry/SentryClientTest.kt @@ -287,6 +287,15 @@ class SentryClientTest { verify(onDiscardMock).execute(DiscardReason.CALLBACK_ERROR, DataCategory.Error, 1) } + @Test + fun `when beforeSend throws a fatal error, it propagates`() { + fixture.sentryOptions.setBeforeSend { _, _ -> throw OutOfMemoryError("test") } + val sut = fixture.getSut() + + assertFailsWith { sut.captureEvent(SentryEvent()) } + verifyNoInteractions(fixture.transport) + } + @Test fun `when beforeSend captures another event, the nested capture is dropped and does not recurse`() { var invocations = 0 diff --git a/sentry/src/test/java/io/sentry/SentryTest.kt b/sentry/src/test/java/io/sentry/SentryTest.kt index 9fb60f6922f..9b0ef61b4bd 100644 --- a/sentry/src/test/java/io/sentry/SentryTest.kt +++ b/sentry/src/test/java/io/sentry/SentryTest.kt @@ -39,6 +39,7 @@ import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFails +import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertNotEquals @@ -1517,6 +1518,32 @@ class SentryTest { } } + @Test + fun `scope callbacks that throw a runtime exception are swallowed`() { + initForTest { o -> o.dsn = dsn } + + Sentry.withScope { throw IllegalStateException("withScope") } + Sentry.withIsolationScope { throw IllegalStateException("withIsolationScope") } + Sentry.configureScope { throw IllegalStateException("configureScope") } + ScopesAdapter.getInstance().withScope { throw IllegalStateException("adapter withScope") } + } + + @Test + fun `scope callbacks that throw a fatal error propagate`() { + initForTest { o -> o.dsn = dsn } + + assertFailsWith { Sentry.withScope { throw OutOfMemoryError("withScope") } } + assertFailsWith { + Sentry.withIsolationScope { throw OutOfMemoryError("withIsolationScope") } + } + assertFailsWith { + Sentry.configureScope { throw OutOfMemoryError("configureScope") } + } + assertFailsWith { + ScopesAdapter.getInstance().configureScope { throw OutOfMemoryError("adapter") } + } + } + @Test fun `withScope data does not leak into events captured after the callback`() { for (globalHubMode in listOf(false, true)) { diff --git a/sentry/src/test/java/io/sentry/TracesSamplerTest.kt b/sentry/src/test/java/io/sentry/TracesSamplerTest.kt index 28a3c4e52c7..5a5c0fb0dc1 100644 --- a/sentry/src/test/java/io/sentry/TracesSamplerTest.kt +++ b/sentry/src/test/java/io/sentry/TracesSamplerTest.kt @@ -8,6 +8,7 @@ import io.sentry.protocol.SentryId import io.sentry.util.SentryRandom import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull @@ -459,6 +460,24 @@ class TracesSamplerTest { verify(logger).log(eq(SentryLevel.ERROR), any(), eq(exception)) } + @Test + fun `when TracesSamplerCallback throws a fatal error, it propagates`() { + val sampler = fixture.getSut(tracesSamplerCallback = { throw OutOfMemoryError("test") }) + + assertFailsWith { + sampler.sample(SamplingContext(TransactionContext("name", "op"), null, 0.1, null)) + } + } + + @Test + fun `when ProfilesSamplerCallback throws a fatal error, it propagates`() { + val sampler = fixture.getSut(profilesSamplerCallback = { throw OutOfMemoryError("test") }) + + assertFailsWith { + sampler.sample(SamplingContext(TransactionContext("name", "op"), null, 0.1, null)) + } + } + @Test fun `when tracesSampler throws without a parent then static rates are ignored`() { val exception = Exception("faulty TracesSamplerCallback") From e0845ceaeb87ada74dc331a67b2effe2528e024b Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Wed, 18 Nov 2026 17:32:10 +0100 Subject: [PATCH 2/5] changelog Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index be7899e2dd6..759a5fcd4af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -83,6 +83,9 @@ - Nav3: Returning to an Activity or Fragment with its own `SentryNavEffect` within the app (e.g., closing the Activity that covered it, swiping back to its ViewPager2 page, or dismissing a dialog over it) now starts a new navigation transaction for the current destination if the previous one finished, so spans produced upon return can now be consistently captured ([#6482](https://github.com/getsentry/sentry-java/pull/6482)) - Nav3: `ui.load` transactions are bound to `IScope` in preference to Nav3 transactions when transitioning between Activities, matching Nav2 behavior (API 29+) ([#6484](https://github.com/getsentry/sentry-java/pull/6484)) +- The SDK no longer swallows fatal errors such as `OutOfMemoryError` and `StackOverflowError`. They now propagate to the caller, for example out of `Sentry.captureException` or from a throwing `beforeSend` callback, instead of only being logged ([#6665](https://github.com/getsentry/sentry-java/pull/6665)) + - `LinkageError`s propagate too, except where the SDK expects them because an optional dependency is missing or has an incompatible version. + - Other exceptions thrown by your callbacks are still caught and logged at `ERROR`, which prints only with `debug` enabled. ### Improvements From 9df2aa848dcb6ac1798073f4b261c397417fe30e Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Wed, 18 Nov 2026 18:33:38 +0100 Subject: [PATCH 3/5] test: Remove the tests added for rethrowing fatal errors Refs #5513 Refs JAVA-552 Co-Authored-By: Claude Opus 5.5 --- .../io/sentry/android/core/ANRWatchDogTest.kt | 83 -------------- .../android/core/AnrV2IntegrationTest.kt | 20 ---- .../sentry/android/core/SentryAndroidTest.kt | 13 --- .../apollo3/SentryApollo3InterceptorTest.kt | 21 ---- .../SentryApollo4HttpInterceptorTest.kt | 21 ---- .../io/sentry/logback/SentryAppenderTest.kt | 17 --- sentry/src/test/java/io/sentry/ScopeTest.kt | 12 --- sentry/src/test/java/io/sentry/ScopesTest.kt | 102 ------------------ .../test/java/io/sentry/SentryClientTest.kt | 9 -- sentry/src/test/java/io/sentry/SentryTest.kt | 27 ----- .../test/java/io/sentry/TracesSamplerTest.kt | 19 ---- 11 files changed, 344 deletions(-) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/ANRWatchDogTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/ANRWatchDogTest.kt index dad5fa9c290..fa0f8a7b2fa 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/ANRWatchDogTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/ANRWatchDogTest.kt @@ -4,27 +4,20 @@ import android.app.ActivityManager import android.app.ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING import android.app.ActivityManager.ProcessErrorStateInfo.NO_ERROR import android.content.Context -import com.google.common.truth.Truth.assertThat import io.sentry.time.TestMonotonicTicker import java.util.concurrent.CountDownLatch -import java.util.concurrent.ExecutionException import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit.MILLISECONDS import kotlin.test.Test import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue import org.junit.Before import org.mockito.kotlin.any -import org.mockito.kotlin.atLeastOnce import org.mockito.kotlin.eq import org.mockito.kotlin.mock -import org.mockito.kotlin.mockingDetails -import org.mockito.kotlin.verify import org.mockito.kotlin.whenever class ANRWatchDogTest { @@ -236,82 +229,6 @@ class ANRWatchDogTest { } } - @Test - fun `when getProcessesInErrorState runs out of memory, keeps watching without reporting`() { - var anr: ApplicationNotResponding? = null - val am = mock() - whenever(am.processesInErrorState).thenThrow(OutOfMemoryError("large reply")) - val posted = CountDownLatch(1) - val sut = watchDog(am, posted) { a -> anr = a } - val es = Executors.newSingleThreadExecutor() - try { - val running = es.submit { sut.run() } - assertTrue(posted.await(10L, TimeUnit.SECONDS)) - - var waitCount = 0 - do { - ticker.advance(100, MILLISECONDS) - Thread.sleep(100L) - } while (mockingDetails(am).invocations.isEmpty() && waitCount++ < 100) - - verify(am, atLeastOnce()).processesInErrorState - assertNull(anr) - assertFalse(running.isDone) - } finally { - sut.interrupt() - es.shutdown() - } - } - - @Test - fun `when getProcessesInErrorState throws a fatal error, the watchdog stops`() { - val am = mock() - whenever(am.processesInErrorState).thenThrow(StackOverflowError()) - val posted = CountDownLatch(1) - val sut = watchDog(am, posted) {} - val es = Executors.newSingleThreadExecutor() - try { - val running = es.submit { sut.run() } - assertTrue(posted.await(10L, TimeUnit.SECONDS)) - - var waitCount = 0 - do { - ticker.advance(100, MILLISECONDS) - Thread.sleep(100L) - } while (!running.isDone && waitCount++ < 100) - - val error = assertFailsWith { running.get() } - assertThat(error.cause).isInstanceOf(StackOverflowError::class.java) - } finally { - sut.interrupt() - es.shutdown() - } - } - - private fun watchDog( - am: ActivityManager, - posted: CountDownLatch, - listener: ANRWatchDog.ANRListener, - ): ANRWatchDog { - val handler = mock() - // the posted runnable never runs, so the main thread looks blocked - whenever(handler.post(any())).then { posted.countDown() } - whenever(handler.thread).thenReturn(mock()) - val context = mock() - whenever(context.getSystemService(eq(Context.ACTIVITY_SERVICE))).thenReturn(am) - return ANRWatchDog( - ticker, - 10L, - 1L, - true, - listener, - mock(), - handler, - context, - AndroidDebugManager(), - ) - } - @Test fun `measures the ANR threshold on the ticker, not on wall time`() { var anr: ApplicationNotResponding? = null diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/AnrV2IntegrationTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AnrV2IntegrationTest.kt index 8c78fe22897..5d43c28ede3 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/AnrV2IntegrationTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/AnrV2IntegrationTest.kt @@ -237,26 +237,6 @@ class AnrV2IntegrationTest : ApplicationExitIntegrationTestBase() { verify(fixture.scopes, never()).captureEvent(any(), anyOrNull()) } - @Test - fun `when reading the trace throws a runtime exception, does not report ANR`() { - val integration = fixture.getSut(tmpDir, lastReportedTimestamp = oldTimestamp) - val exitInfo = - spy( - ApplicationExitInfoBuilder.newBuilder() - .setReason(ApplicationExitInfo.REASON_ANR) - .setTimestamp(newTimestamp) - .build(), - ) { - // getTraceInputStream() is a Binder call, which rethrows exceptions from system_server - whenever(mock.traceInputStream).thenThrow(SecurityException("denied")) - } - fixture.shadowActivityManager.addApplicationExitInfo(exitInfo) - - integration.register(fixture.scopes, fixture.options) - - verify(fixture.scopes, never()).captureEvent(any(), anyOrNull()) - } - @Test fun `when traceInputStream has bad data, does not report ANR`() { val integration = fixture.getSut(tmpDir, lastReportedTimestamp = oldTimestamp) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt index b400bb4707c..dc2472e6a6d 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt @@ -217,19 +217,6 @@ class SentryAndroidTest { assertTrue(Sentry.isEnabled()) } - @Test - fun `when the configuration handler throws, init continues with the options it set`() { - var refOptions: SentryAndroidOptions? = null - fixture.initSut { - it.anrTimeoutIntervalMillis = 3000 - refOptions = it - throw IllegalStateException("configuration failed") - } - - assertEquals(3000, refOptions!!.anrTimeoutIntervalMillis) - assertTrue(Sentry.isEnabled()) - } - @Test fun `init won't throw exception`() { val logger = mock() diff --git a/sentry-apollo-3/src/test/java/io/sentry/apollo3/SentryApollo3InterceptorTest.kt b/sentry-apollo-3/src/test/java/io/sentry/apollo3/SentryApollo3InterceptorTest.kt index f18bc20a8ad..7b9454f394a 100644 --- a/sentry-apollo-3/src/test/java/io/sentry/apollo3/SentryApollo3InterceptorTest.kt +++ b/sentry-apollo-3/src/test/java/io/sentry/apollo3/SentryApollo3InterceptorTest.kt @@ -484,27 +484,6 @@ class SentryApollo3InterceptorTest { ) } - @Test - fun `when beforeSpan throws a fatal error, rethrows it`(): Unit = runBlocking { - val tx = - SentryTracer(TransactionContext("op", "desc", TracesSamplingDecision(true)), fixture.scopes) - whenever(fixture.scopes.span).thenReturn(tx) - val chain = - object : HttpInterceptorChain { - override suspend fun proceed(request: HttpRequest): HttpResponse = - HttpResponse.Builder(200).build() - } - val request = HttpRequest.Builder(HttpMethod.Post, "https://example.com/graphql").build() - val interceptor = - SentryApollo3HttpInterceptor( - fixture.scopes, - { _, _, _ -> throw OutOfMemoryError("callback") }, - captureFailedRequests = false, - ) - - assertFailsWith { interceptor.intercept(request, chain) } - } - @Test fun `adds breadcrumb when http calls succeeds`() { executeQuery(fixture.getSut()) diff --git a/sentry-apollo-4/src/test/java/io/sentry/apollo4/SentryApollo4HttpInterceptorTest.kt b/sentry-apollo-4/src/test/java/io/sentry/apollo4/SentryApollo4HttpInterceptorTest.kt index b32c822981a..cb78ddcbd05 100644 --- a/sentry-apollo-4/src/test/java/io/sentry/apollo4/SentryApollo4HttpInterceptorTest.kt +++ b/sentry-apollo-4/src/test/java/io/sentry/apollo4/SentryApollo4HttpInterceptorTest.kt @@ -498,27 +498,6 @@ abstract class SentryApollo4HttpInterceptorTest( ) } - @Test - fun `when beforeSpan throws a fatal error, rethrows it`(): Unit = runBlocking { - val tx = - SentryTracer(TransactionContext("op", "desc", TracesSamplingDecision(true)), fixture.scopes) - whenever(fixture.scopes.span).thenReturn(tx) - val chain = - object : HttpInterceptorChain { - override suspend fun proceed(request: HttpRequest): HttpResponse = - HttpResponse.Builder(200).build() - } - val request = HttpRequest.Builder(HttpMethod.Post, "https://example.com/graphql").build() - val interceptor = - SentryApollo4HttpInterceptor( - fixture.scopes, - { _, _, _ -> throw OutOfMemoryError("callback") }, - captureFailedRequests = false, - ) - - assertFailsWith { interceptor.intercept(request, chain) } - } - @Test fun `adds breadcrumb when http calls succeeds`() { executeQuery(fixture.getSut()) diff --git a/sentry-logback/src/test/kotlin/io/sentry/logback/SentryAppenderTest.kt b/sentry-logback/src/test/kotlin/io/sentry/logback/SentryAppenderTest.kt index 04b3a97da14..a5ecb2b30cd 100644 --- a/sentry-logback/src/test/kotlin/io/sentry/logback/SentryAppenderTest.kt +++ b/sentry-logback/src/test/kotlin/io/sentry/logback/SentryAppenderTest.kt @@ -32,7 +32,6 @@ import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals -import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull @@ -330,22 +329,6 @@ class SentryAppenderTest { ) } - class FatalEncoder : EncoderBase() { - override fun headerBytes(): ByteArray = ByteArray(0) - - override fun footerBytes(): ByteArray = ByteArray(0) - - override fun encode(event: ILoggingEvent?): ByteArray = throw OutOfMemoryError("encoder") - } - - @Test - fun `rethrows a fatal error from the encoder`() { - fixture = - Fixture(minimumEventLevel = Level.DEBUG, encoder = FatalEncoder(), sendDefaultPii = true) - - assertFailsWith { fixture.logger.info("testing a fatal encoder error") } - } - @Test fun `event date is in UTC`() { fixture = Fixture(minimumEventLevel = Level.DEBUG) diff --git a/sentry/src/test/java/io/sentry/ScopeTest.kt b/sentry/src/test/java/io/sentry/ScopeTest.kt index ae3e67ffc45..536f869ebc8 100644 --- a/sentry/src/test/java/io/sentry/ScopeTest.kt +++ b/sentry/src/test/java/io/sentry/ScopeTest.kt @@ -10,7 +10,6 @@ import io.sentry.test.callMethod import java.util.concurrent.CopyOnWriteArrayList import kotlin.test.Test import kotlin.test.assertEquals -import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNotSame @@ -379,17 +378,6 @@ class ScopeTest { assertThat(scope.breadcrumbs.single().message).isEqualTo("kept") } - @Test - fun `when beforeBreadcrumb throws a fatal error, it propagates`() { - val options = - SentryOptions().apply { setBeforeBreadcrumb { _, _ -> throw OutOfMemoryError("test") } } - - val scope = Scope(options) - - assertFailsWith { scope.addBreadcrumb(Breadcrumb()) } - assertThat(scope.breadcrumbs).isEmpty() - } - @Test fun `when adding breadcrumb, executeBreadcrumb wont be executed as its not set, but it will be added`() { val options = SentryOptions() diff --git a/sentry/src/test/java/io/sentry/ScopesTest.kt b/sentry/src/test/java/io/sentry/ScopesTest.kt index 5ea0ed739aa..15e1d82941d 100644 --- a/sentry/src/test/java/io/sentry/ScopesTest.kt +++ b/sentry/src/test/java/io/sentry/ScopesTest.kt @@ -785,35 +785,6 @@ class ScopesTest { verify(logger).log(eq(SentryLevel.ERROR), any(), eq(exception)) } - @Test - fun `when captureException is called with a ScopeCallback that throws a fatal error, it propagates`() { - val (sut, mockClient) = getEnabledScopes() - - assertFailsWith { - sut.captureException(Throwable()) { throw OutOfMemoryError("scope callback") } - } - verify(mockClient, never()).captureEvent(any(), anyOrNull(), anyOrNull()) - } - - @Test - fun `when the client throws a fatal error while capturing, it propagates`() { - val (sut, mockClient) = getEnabledScopes() - whenever(mockClient.captureEvent(any(), anyOrNull(), anyOrNull())) - .thenThrow(OutOfMemoryError("client")) - - assertFailsWith { sut.captureException(Throwable()) } - } - - @Test - fun `when the client throws a runtime exception while capturing, it is logged`() { - val (sut, mockClient, logger) = getEnabledScopes() - val exception = IllegalStateException("client") - whenever(mockClient.captureEvent(any(), anyOrNull(), anyOrNull())).thenThrow(exception) - - assertThat(sut.captureException(Throwable())).isEqualTo(SentryId.EMPTY_ID) - verify(logger).log(eq(SentryLevel.ERROR), any(), eq(exception)) - } - // endregion // region captureCheckIn tests @@ -928,31 +899,6 @@ class ScopesTest { verify(logger).log(eq(SentryLevel.ERROR), any(), eq(exception)) } - @Test - fun `when withScope throws a runtime exception then it is swallowed`() { - val (scopes, _, logger) = getEnabledScopes() - val exception = IllegalStateException("scope callback exception") - - scopes.withScope { throw exception } - - verify(logger).log(eq(SentryLevel.ERROR), any(), eq(exception)) - } - - @Test - fun `when withScope throws a fatal error then it propagates`() { - val (scopes) = getEnabledScopes() - - assertFailsWith { scopes.withScope { throw OutOfMemoryError("callback") } } - } - - @Test - fun `when withScope on a closed scopes throws a fatal error then it propagates`() { - val (scopes) = getEnabledScopes() - scopes.close() - - assertFailsWith { scopes.withScope { throw OutOfMemoryError("callback") } } - } - // endregion // region withIsolationScope tests @@ -989,35 +935,6 @@ class ScopesTest { verify(logger).log(eq(SentryLevel.ERROR), any(), eq(exception)) } - @Test - fun `when withIsolationScope throws a runtime exception then it is swallowed`() { - val (scopes, _, logger) = getEnabledScopes() - val exception = IllegalStateException("scope callback exception") - - scopes.withIsolationScope { throw exception } - - verify(logger).log(eq(SentryLevel.ERROR), any(), eq(exception)) - } - - @Test - fun `when withIsolationScope throws a fatal error then it propagates`() { - val (scopes) = getEnabledScopes() - - assertFailsWith { - scopes.withIsolationScope { throw OutOfMemoryError("callback") } - } - } - - @Test - fun `when withIsolationScope on a closed scopes throws a fatal error then it propagates`() { - val (scopes) = getEnabledScopes() - scopes.close() - - assertFailsWith { - scopes.withIsolationScope { throw OutOfMemoryError("callback") } - } - } - // endregion // region configureScope tests @@ -1054,25 +971,6 @@ class ScopesTest { verify(logger).log(eq(SentryLevel.ERROR), any(), eq(exception)) } - @Test - fun `when configureScope throws a runtime exception then it is swallowed`() { - val (scopes, _, logger) = getEnabledScopes() - val exception = IllegalStateException("scope callback exception") - - scopes.configureScope { throw exception } - - verify(logger).log(eq(SentryLevel.ERROR), any(), eq(exception)) - } - - @Test - fun `when configureScope throws a fatal error then it propagates`() { - val (scopes) = getEnabledScopes() - - assertFailsWith { - scopes.configureScope { throw OutOfMemoryError("callback") } - } - } - // endregion @Test diff --git a/sentry/src/test/java/io/sentry/SentryClientTest.kt b/sentry/src/test/java/io/sentry/SentryClientTest.kt index dd3acf2e274..c1e96f842b7 100644 --- a/sentry/src/test/java/io/sentry/SentryClientTest.kt +++ b/sentry/src/test/java/io/sentry/SentryClientTest.kt @@ -287,15 +287,6 @@ class SentryClientTest { verify(onDiscardMock).execute(DiscardReason.CALLBACK_ERROR, DataCategory.Error, 1) } - @Test - fun `when beforeSend throws a fatal error, it propagates`() { - fixture.sentryOptions.setBeforeSend { _, _ -> throw OutOfMemoryError("test") } - val sut = fixture.getSut() - - assertFailsWith { sut.captureEvent(SentryEvent()) } - verifyNoInteractions(fixture.transport) - } - @Test fun `when beforeSend captures another event, the nested capture is dropped and does not recurse`() { var invocations = 0 diff --git a/sentry/src/test/java/io/sentry/SentryTest.kt b/sentry/src/test/java/io/sentry/SentryTest.kt index 9b0ef61b4bd..9fb60f6922f 100644 --- a/sentry/src/test/java/io/sentry/SentryTest.kt +++ b/sentry/src/test/java/io/sentry/SentryTest.kt @@ -39,7 +39,6 @@ import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFails -import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertNotEquals @@ -1518,32 +1517,6 @@ class SentryTest { } } - @Test - fun `scope callbacks that throw a runtime exception are swallowed`() { - initForTest { o -> o.dsn = dsn } - - Sentry.withScope { throw IllegalStateException("withScope") } - Sentry.withIsolationScope { throw IllegalStateException("withIsolationScope") } - Sentry.configureScope { throw IllegalStateException("configureScope") } - ScopesAdapter.getInstance().withScope { throw IllegalStateException("adapter withScope") } - } - - @Test - fun `scope callbacks that throw a fatal error propagate`() { - initForTest { o -> o.dsn = dsn } - - assertFailsWith { Sentry.withScope { throw OutOfMemoryError("withScope") } } - assertFailsWith { - Sentry.withIsolationScope { throw OutOfMemoryError("withIsolationScope") } - } - assertFailsWith { - Sentry.configureScope { throw OutOfMemoryError("configureScope") } - } - assertFailsWith { - ScopesAdapter.getInstance().configureScope { throw OutOfMemoryError("adapter") } - } - } - @Test fun `withScope data does not leak into events captured after the callback`() { for (globalHubMode in listOf(false, true)) { diff --git a/sentry/src/test/java/io/sentry/TracesSamplerTest.kt b/sentry/src/test/java/io/sentry/TracesSamplerTest.kt index 5a5c0fb0dc1..28a3c4e52c7 100644 --- a/sentry/src/test/java/io/sentry/TracesSamplerTest.kt +++ b/sentry/src/test/java/io/sentry/TracesSamplerTest.kt @@ -8,7 +8,6 @@ import io.sentry.protocol.SentryId import io.sentry.util.SentryRandom import kotlin.test.Test import kotlin.test.assertEquals -import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull @@ -460,24 +459,6 @@ class TracesSamplerTest { verify(logger).log(eq(SentryLevel.ERROR), any(), eq(exception)) } - @Test - fun `when TracesSamplerCallback throws a fatal error, it propagates`() { - val sampler = fixture.getSut(tracesSamplerCallback = { throw OutOfMemoryError("test") }) - - assertFailsWith { - sampler.sample(SamplingContext(TransactionContext("name", "op"), null, 0.1, null)) - } - } - - @Test - fun `when ProfilesSamplerCallback throws a fatal error, it propagates`() { - val sampler = fixture.getSut(profilesSamplerCallback = { throw OutOfMemoryError("test") }) - - assertFailsWith { - sampler.sample(SamplingContext(TransactionContext("name", "op"), null, 0.1, null)) - } - } - @Test fun `when tracesSampler throws without a parent then static rates are ignored`() { val exception = Exception("faulty TracesSamplerCallback") From d492676db8cf42a2aa92b6f0554cc92122178dd6 Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Wed, 18 Nov 2026 18:35:13 +0100 Subject: [PATCH 4/5] changelog Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 759a5fcd4af..a042bb63a3b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -83,9 +83,7 @@ - Nav3: Returning to an Activity or Fragment with its own `SentryNavEffect` within the app (e.g., closing the Activity that covered it, swiping back to its ViewPager2 page, or dismissing a dialog over it) now starts a new navigation transaction for the current destination if the previous one finished, so spans produced upon return can now be consistently captured ([#6482](https://github.com/getsentry/sentry-java/pull/6482)) - Nav3: `ui.load` transactions are bound to `IScope` in preference to Nav3 transactions when transitioning between Activities, matching Nav2 behavior (API 29+) ([#6484](https://github.com/getsentry/sentry-java/pull/6484)) -- The SDK no longer swallows fatal errors such as `OutOfMemoryError` and `StackOverflowError`. They now propagate to the caller, for example out of `Sentry.captureException` or from a throwing `beforeSend` callback, instead of only being logged ([#6665](https://github.com/getsentry/sentry-java/pull/6665)) - - `LinkageError`s propagate too, except where the SDK expects them because an optional dependency is missing or has an incompatible version. - - Other exceptions thrown by your callbacks are still caught and logged at `ERROR`, which prints only with `debug` enabled. +- The SDK no longer swallows fatal errors such as `OutOfMemoryError`, `StackOverflowError` or an unexpected `LinkageError`, nor its own bugs: its `catch (Throwable)` sites now catch only what they guard. This also stops `QueueFile` from deleting its file on an `OutOfMemoryError`, `Installation` from wrapping an `OutOfMemoryError`, and the Ktor client integration from swallowing coroutine cancellation ([#6665](https://github.com/getsentry/sentry-java/pull/6665), [#6666](https://github.com/getsentry/sentry-java/pull/6666), [#6667](https://github.com/getsentry/sentry-java/pull/6667), [#6668](https://github.com/getsentry/sentry-java/pull/6668), [#6669](https://github.com/getsentry/sentry-java/pull/6669), [#6670](https://github.com/getsentry/sentry-java/pull/6670)) ### Improvements From d79261db5bc1a53de283bdd23fe5d0399667c4e7 Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Wed, 18 Nov 2026 18:36:29 +0100 Subject: [PATCH 5/5] ref(core): Leave the client report attach catch to the narrowing PR Narrowing attachReportToEnvelope to IOException is a narrowing, not a boundary, so it moves to the PR that narrows catches. Refs #5513 Refs JAVA-552 Co-Authored-By: Claude Opus 5.5 --- .../main/java/io/sentry/clientreport/ClientReportRecorder.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/sentry/src/main/java/io/sentry/clientreport/ClientReportRecorder.java b/sentry/src/main/java/io/sentry/clientreport/ClientReportRecorder.java index e8e49039173..f5e517faac0 100644 --- a/sentry/src/main/java/io/sentry/clientreport/ClientReportRecorder.java +++ b/sentry/src/main/java/io/sentry/clientreport/ClientReportRecorder.java @@ -10,7 +10,6 @@ import io.sentry.protocol.SentrySpan; import io.sentry.protocol.SentryTransaction; import io.sentry.util.ExceptionUtils; -import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -48,7 +47,7 @@ public ClientReportRecorder(@NotNull SentryOptions options) { items.add(SentryEnvelopeItem.fromClientReport(options.getSerializer(), clientReport)); return new SentryEnvelope(envelope.getHeader(), items); - } catch (IOException e) { + } catch (Throwable e) { options.getLogger().log(SentryLevel.ERROR, e, "Unable to attach client report to envelope."); return envelope; }