diff --git a/CHANGELOG.md b/CHANGELOG.md index d4d98889d0..3aab60a724 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 ([#6657](https://github.com/getsentry/sentry-java/pull/6657)) + - `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 diff --git a/sentry/src/main/java/io/sentry/DirectoryProcessor.java b/sentry/src/main/java/io/sentry/DirectoryProcessor.java index d9f0f32c40..2870fb4b35 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 0aed2d6261..1a77a6ed07 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 928fd02209..05f600d4bd 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/JsonSerializer.java b/sentry/src/main/java/io/sentry/JsonSerializer.java index d8b02c1a1c..cf94708eba 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 21952dc0c5..2f25a0a8f3 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 4e3b2e9b3d..9330788981 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 aee42fa07d..7e126ec6de 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 b05e4d9d05..e07156b862 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 96d15c29f7..baa0c93d28 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 75c263c412..87899ad400 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( @@ -417,7 +436,16 @@ public void close(final boolean isRestarting) { if (integration instanceof Closeable) { try { ((Closeable) integration).close(); + } catch (LinkageError e) { + // The integration needs an optional dependency that is missing or has an + // incompatible version. The remaining integrations are still closed. + getOptions() + .getLogger() + .log(SentryLevel.WARNING, "Failed to close the integration {}.", integration, e); } catch (Throwable e) { + // Integrations can be user-provided, so we can't know what they throw. The + // remaining integrations are still closed. + ExceptionUtils.rethrowIfFatal(e); getOptions() .getLogger() .log(SentryLevel.WARNING, "Failed to close the integration {}.", integration, e); @@ -429,6 +457,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( @@ -476,6 +507,9 @@ public void close(final boolean isRestarting) { configureScope(ScopeType.ISOLATION, scope -> scope.getClient().close(isRestarting)); configureScope(ScopeType.GLOBAL, scope -> scope.getClient().close(isRestarting)); } catch (Throwable e) { + // A public API entry point: closing shuts down components that integrations and the app + // can replace, so we can't know what it throws. The remaining shutdown steps are skipped. + ExceptionUtils.rethrowIfFatal(e); getOptions().getLogger().log(SentryLevel.ERROR, "Error while closing the Scopes.", e); } } @@ -670,6 +704,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 +714,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 +727,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 +739,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 +761,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 +796,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 +868,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 +902,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 +1200,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 +1226,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 a9a8c1d8fe..3ef1161a2a 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 7f7879864e..b769b50ddb 100644 --- a/sentry/src/main/java/io/sentry/Sentry.java +++ b/sentry/src/main/java/io/sentry/Sentry.java @@ -254,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); @@ -1281,6 +1284,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 b502743262..b4f55eb9f9 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( @@ -494,6 +498,13 @@ private SentryEvent processEvent( event = processor.process(event, hint); } } catch (Throwable e) { + // Event processors come from integrations and the app, so we can't know what they throw. + // An SDK processor is skipped; any other processor's failure drops the event. + // A LinkageError means the processor needs an optional dependency that is missing or has an + // incompatible version, which is handled like any other failure. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } options .getLogger() .log( @@ -551,6 +562,13 @@ private SentryLogEvent processLogEvent( try { event = processor.process(event); } catch (Throwable e) { + // Event processors come from integrations and the app, so we can't know what they throw. + // An SDK processor is skipped; any other processor's failure drops the log. + // A LinkageError means the processor needs an optional dependency that is missing or has an + // incompatible version, which is handled like any other failure. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } options .getLogger() .log( @@ -588,6 +606,13 @@ private SentryMetricsEvent processMetricsEvent( try { event = processor.process(event, hint); } catch (Throwable e) { + // Event processors come from integrations and the app, so we can't know what they throw. + // An SDK processor is skipped; any other processor's failure drops the metric. + // A LinkageError means the processor needs an optional dependency that is missing or has an + // incompatible version, which is handled like any other failure. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } options .getLogger() .log( @@ -625,6 +650,13 @@ private SentryMetricsEvent processMetricsEvent( try { transaction = processor.process(transaction, hint); } catch (Throwable e) { + // Event processors come from integrations and the app, so we can't know what they throw. + // An SDK processor is skipped; any other processor's failure drops the transaction. + // A LinkageError means the processor needs an optional dependency that is missing or has an + // incompatible version, which is handled like any other failure. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } options .getLogger() .log( @@ -698,6 +730,13 @@ private SentryReplayEvent processReplayEvent( try { replayEvent = processor.process(replayEvent, hint); } catch (Throwable e) { + // Event processors come from integrations and the app, so we can't know what they throw. + // An SDK processor is skipped; any other processor's failure drops the replay segment. + // A LinkageError means the processor needs an optional dependency that is missing or has an + // incompatible version, which is handled like any other failure. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } options .getLogger() .log( @@ -738,6 +777,13 @@ private SentryEvent processFeedbackEvent( try { feedbackEvent = processor.process(feedbackEvent, hint); } catch (Throwable e) { + // Event processors come from integrations and the app, so we can't know what they throw. + // An SDK processor is skipped; any other processor's failure drops the feedback. + // A LinkageError means the processor needs an optional dependency that is missing or has an + // incompatible version, which is handled like any other failure. + if (!(e instanceof LinkageError)) { + ExceptionUtils.rethrowIfFatal(e); + } options .getLogger() .log( @@ -953,6 +999,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 +1690,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 +1722,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 +1785,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 +1815,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 +1846,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 +1873,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 2873d2c8ad..b635c9fbd5 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 eaacee9957..391b954394 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; } } @@ -62,7 +66,9 @@ Integer getMetaLength() { if (calculateMetaLength != null) { try { return calculateMetaLength.call(); - } catch (Throwable ignored) { + } catch (Exception e) { + // Callable.call() declares Exception, but the only factory reads a value that the data + // factory stored. The header is written without a meta length. return null; } } diff --git a/sentry/src/main/java/io/sentry/SentryOptions.java b/sentry/src/main/java/io/sentry/SentryOptions.java index 60b1f3cd42..df9af9103d 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 a068e12f2a..332854a0d8 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 diff --git a/sentry/src/main/java/io/sentry/TracesSampler.java b/sentry/src/main/java/io/sentry/TracesSampler.java index bb6e5d9f11..d1779f9324 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/cache/CacheStrategy.java b/sentry/src/main/java/io/sentry/cache/CacheStrategy.java index 5f3e605f2a..9747fff1a2 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 142b7c3fda..b53c833ff8 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 3fde2a97f5..870b5c9d9c 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 cf3bfcb3d1..9337138a30 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 ba6d60e256..4b0d4476b9 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; } @@ -58,12 +60,8 @@ public void recordLostEnvelope(@NotNull DiscardReason reason, @Nullable SentryEn return; } - try { - for (final SentryEnvelopeItem item : envelope.getItems()) { - recordLostEnvelopeItem(reason, item); - } - } catch (Throwable e) { - options.getLogger().log(SentryLevel.ERROR, e, "Unable to record lost envelope."); + for (final SentryEnvelopeItem item : envelope.getItems()) { + recordLostEnvelopeItem(reason, item); } } @@ -125,6 +123,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."); } } @@ -137,12 +138,8 @@ public void recordLostEvent(@NotNull DiscardReason reason, @NotNull DataCategory @Override public void recordLostEvent( @NotNull DiscardReason reason, @NotNull DataCategory category, long count) { - try { - recordLostEventInternal(reason.getReason(), category.getCategory(), count); - executeOnDiscard(reason, category, count); - } catch (Throwable e) { - options.getLogger().log(SentryLevel.ERROR, e, "Unable to record lost event."); - } + recordLostEventInternal(reason.getReason(), category.getCategory(), count); + executeOnDiscard(reason, category, count); } private void executeOnDiscard( @@ -151,6 +148,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 1933d7f0fe..a5a6e4a89c 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 9648b99d37..a92e431821 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 34abeb3183..dbbf7fbbfe 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 c24f96dbff..81a212a5cb 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 c6c3d1a48b..e8423fb720 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 e515ef6fd6..5b94543a58 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 536f869ebc..ae3e67ffc4 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 15e1d82941..acd2b764ad 100644 --- a/sentry/src/test/java/io/sentry/ScopesTest.kt +++ b/sentry/src/test/java/io/sentry/ScopesTest.kt @@ -22,6 +22,7 @@ import io.sentry.test.createTestScopes import io.sentry.test.initForTest import io.sentry.util.HintUtils import io.sentry.util.StringUtils +import java.io.Closeable import java.io.File import java.nio.file.Files import java.util.Queue @@ -785,6 +786,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 @@ -830,6 +860,33 @@ class ScopesTest { // endregion // region close tests + @Test + fun `when an integration's close throws a LinkageError, the other integrations are still closed`() { + val failing = mock(extraInterfaces = arrayOf(Closeable::class)) + doThrow(NoClassDefFoundError("missing")).whenever(failing as Closeable).close() + val next = mock(extraInterfaces = arrayOf(Closeable::class)) + val (sut) = + getEnabledScopes { + it.addIntegration(failing) + it.addIntegration(next) + } + + sut.close() + + verify(next as Closeable).close() + } + + @Test + fun `when an integration's close throws a fatal error, it propagates`() { + val failing = mock(extraInterfaces = arrayOf(Closeable::class)) + doThrow(OutOfMemoryError("close")).whenever(failing as Closeable).close() + val (sut) = getEnabledScopes { it.addIntegration(failing) } + + assertFailsWith { sut.close() } + // the scopes are closed again after the test + reset(failing) + } + @Test fun `when close is called on disabled client, do nothing`() { val (sut, mockClient) = getEnabledScopes() diff --git a/sentry/src/test/java/io/sentry/SentryClientTest.kt b/sentry/src/test/java/io/sentry/SentryClientTest.kt index c1e96f842b..2a87309f2a 100644 --- a/sentry/src/test/java/io/sentry/SentryClientTest.kt +++ b/sentry/src/test/java/io/sentry/SentryClientTest.kt @@ -287,6 +287,39 @@ 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 an event processor throws a fatal error, it propagates`() { + val processor = mock() + whenever(processor.process(any(), any())).thenThrow(StackOverflowError()) + fixture.sentryOptions.addEventProcessor(processor) + val sut = fixture.getSut() + + assertFailsWith { sut.captureEvent(SentryEvent()) } + } + + @Test + fun `when an SDK event processor throws a LinkageError, it is skipped and the event is sent`() { + // an SDK processor whose optional dependency is missing at runtime + val processor = mock() + whenever(processor.process(any(), any())) + .thenThrow(NoClassDefFoundError("androidx/Missing")) + fixture.sentryOptions.addEventProcessor(processor) + val sut = fixture.getSut() + + sut.captureEvent(SentryEvent()) + + verify(fixture.transport).send(any(), anyOrNull()) + } + @Test fun `when 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/TracesSamplerTest.kt b/sentry/src/test/java/io/sentry/TracesSamplerTest.kt index 28a3c4e52c..5a5c0fb0dc 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")