Skip to content

Commit 8845736

Browse files
adinauerclaude
andcommitted
fix(integrations): [Callback Errors 9] Guard custom callbacks
Skip Android screenshot and view hierarchy capture when their callbacks throw, while retaining the error event. Drop spans on beforeSpan failures in OkHttp, OpenFeign, GraphQL, Ktor, and Apollo without disrupting requests or replacing the original request error. Preserve normal callback results and existing catch types. Finish failed spans and retain request cleanup and breadcrumbs. Add regression coverage for callback failures, partial mutations, original request errors, asynchronous GraphQL results, and subsequent Android captures. Correct callback wiring in the Ktor and screenshot test fixtures. Verify 18 regression cases fail before the fix and pass afterward; all 454 tests in the affected suites pass, along with formatting and API checks. Refs #6081 Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 7a471df commit 8845736

27 files changed

Lines changed: 602 additions & 22 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,8 @@
127127
- Report attached profiles dropped by transaction callback errors as `callback_error` in client reports and `OnDiscardCallback` ([#6166](https://github.com/getsentry/sentry-java/pull/6166))
128128
- Drop telemetry and record `callback_error` when a customer event processor throws instead of continuing with a potentially partially processed item. SDK-owned processor failures are logged and processing continues without a `callback_error` client report.
129129
- Drop breadcrumbs when `beforeBreadcrumb` throws instead of storing exception details on the breadcrumb.
130+
- Skip Android screenshot or view hierarchy capture when its capture callback throws, while retaining the error event.
131+
- Drop spans when `beforeSpan` throws in OkHttp, OpenFeign, GraphQL, Ktor, or Apollo, without disrupting the request.
130132
- Skip replay capture when `beforeErrorSampling` throws, while still sending the error event ([#6165](https://github.com/getsentry/sentry-java/pull/6165))
131133
- When `tracesSampler` throws, inherit the parent sampling decision or leave the trace unsampled if there is no parent decision, instead of falling back to `tracesSampleRate` ([#6163](https://github.com/getsentry/sentry-java/pull/6163))
132134
- When `profilesSampler` throws, disable profiling instead of falling back to `profilesSampleRate` or inheriting the parent's profiling decision. Trace sampling is unchanged ([#6164](https://github.com/getsentry/sentry-java/pull/6164))

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

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,17 @@ private boolean isMaskingEnabled() {
112112
final @Nullable SentryAndroidOptions.BeforeCaptureCallback beforeCaptureCallback =
113113
options.getBeforeScreenshotCaptureCallback();
114114
if (beforeCaptureCallback != null) {
115-
if (!beforeCaptureCallback.execute(event, hint, shouldDebounce)) {
115+
try {
116+
if (!beforeCaptureCallback.execute(event, hint, shouldDebounce)) {
117+
return event;
118+
}
119+
} catch (Exception e) {
120+
options
121+
.getLogger()
122+
.log(
123+
SentryLevel.ERROR,
124+
"The beforeScreenshotCapture callback threw an exception. Skipping screenshot capture.",
125+
e);
116126
return event;
117127
}
118128
} else if (shouldDebounce) {

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

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,17 @@ public ViewHierarchyEventProcessor(final @NotNull SentryAndroidOptions options)
9191
final @Nullable SentryAndroidOptions.BeforeCaptureCallback beforeCaptureCallback =
9292
options.getBeforeViewHierarchyCaptureCallback();
9393
if (beforeCaptureCallback != null) {
94-
if (!beforeCaptureCallback.execute(event, hint, shouldDebounce)) {
94+
try {
95+
if (!beforeCaptureCallback.execute(event, hint, shouldDebounce)) {
96+
return event;
97+
}
98+
} catch (Exception e) {
99+
options
100+
.getLogger()
101+
.log(
102+
SentryLevel.ERROR,
103+
"The beforeViewHierarchyCapture callback threw an exception. Skipping view hierarchy capture.",
104+
e);
95105
return event;
96106
}
97107
} else if (shouldDebounce) {

‎sentry-android-core/src/test/java/io/sentry/android/core/ScreenshotEventProcessorTest.kt‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,14 @@ import androidx.compose.ui.text.style.TextOverflow
2929
import androidx.compose.ui.unit.dp
3030
import androidx.compose.ui.unit.sp
3131
import androidx.test.ext.junit.runners.AndroidJUnit4
32+
import com.google.common.truth.Truth.assertThat
3233
import io.sentry.Attachment
3334
import io.sentry.Hint
35+
import io.sentry.ILogger
3436
import io.sentry.MainEventProcessor
3537
import io.sentry.SentryEvent
3638
import io.sentry.SentryIntegrationPackageStorage
39+
import io.sentry.SentryLevel
3740
import io.sentry.TypeCheckHint.ANDROID_ACTIVITY
3841
import io.sentry.protocol.SentryException
3942
import io.sentry.util.thread.IThreadChecker
@@ -48,6 +51,7 @@ import kotlin.test.assertSame
4851
import kotlin.test.assertTrue
4952
import org.junit.runner.RunWith
5053
import org.mockito.kotlin.mock
54+
import org.mockito.kotlin.verify
5155
import org.mockito.kotlin.whenever
5256
import org.robolectric.Robolectric.buildActivity
5357
import org.robolectric.Shadows.shadowOf
@@ -310,11 +314,38 @@ class ScreenshotEventProcessorTest {
310314
assertNull(hint.screenshot)
311315
}
312316

317+
@Test
318+
fun `when capture callback throws, skips screenshot and retains event`() {
319+
CurrentActivityHolder.getInstance().setActivity(fixture.activity)
320+
val logger = mock<ILogger>()
321+
fixture.options.isDebug = true
322+
fixture.options.setLogger(logger)
323+
val failure = IllegalStateException("callback failed")
324+
fixture.options.setBeforeScreenshotCaptureCallback { _, _, _ -> throw failure }
325+
val processor = fixture.getSut(true)
326+
val event = SentryEvent().apply { exceptions = listOf(SentryException()) }
327+
val hint = Hint()
328+
329+
assertThat(processor.process(event, hint)).isSameInstanceAs(event)
330+
assertThat(hint.screenshot).isNull()
331+
verify(logger)
332+
.log(
333+
SentryLevel.ERROR,
334+
"The beforeScreenshotCapture callback threw an exception. Skipping screenshot capture.",
335+
failure,
336+
)
337+
338+
fixture.options.setBeforeScreenshotCaptureCallback { _, _, _ -> true }
339+
val nextHint = Hint()
340+
assertThat(processor.process(event, nextHint)).isSameInstanceAs(event)
341+
assertThat(nextHint.screenshot).isNotNull()
342+
}
343+
313344
@Test
314345
fun `when capture callback returns true, a screenshot should be captured`() {
315346
CurrentActivityHolder.getInstance().setActivity(fixture.activity)
316347

317-
fixture.options.setBeforeViewHierarchyCaptureCallback { _, _, _ -> true }
348+
fixture.options.setBeforeScreenshotCaptureCallback { _, _, _ -> true }
318349
val processor = fixture.getSut(true)
319350

320351
val event = SentryEvent().apply { exceptions = listOf(SentryException()) }

‎sentry-android-core/src/test/java/io/sentry/android/core/ViewHierarchyEventProcessorTest.kt‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,13 @@ import android.view.View
55
import android.view.ViewGroup
66
import android.view.Window
77
import androidx.test.ext.junit.runners.AndroidJUnit4
8+
import com.google.common.truth.Truth.assertThat
89
import io.sentry.Hint
910
import io.sentry.JsonSerializable
1011
import io.sentry.JsonSerializer
1112
import io.sentry.SentryEvent
1213
import io.sentry.SentryIntegrationPackageStorage
14+
import io.sentry.SentryLevel
1315
import io.sentry.TypeCheckHint
1416
import io.sentry.protocol.SentryException
1517
import io.sentry.util.thread.IThreadChecker
@@ -342,6 +344,31 @@ class ViewHierarchyEventProcessorTest {
342344
assertNull(hint.viewHierarchy)
343345
}
344346

347+
@Test
348+
fun `when capture callback throws, skips view hierarchy and retains event`() {
349+
fixture.options.isDebug = true
350+
fixture.options.setLogger(fixture.logger)
351+
val failure = IllegalStateException("callback failed")
352+
fixture.options.setBeforeViewHierarchyCaptureCallback { _, _, _ -> throw failure }
353+
val processor = fixture.getSut(true)
354+
val event = SentryEvent().apply { exceptions = listOf(SentryException()) }
355+
val hint = Hint()
356+
357+
assertThat(processor.process(event, hint)).isSameInstanceAs(event)
358+
assertThat(hint.viewHierarchy).isNull()
359+
verify(fixture.logger)
360+
.log(
361+
SentryLevel.ERROR,
362+
"The beforeViewHierarchyCapture callback threw an exception. Skipping view hierarchy capture.",
363+
failure,
364+
)
365+
366+
fixture.options.setBeforeViewHierarchyCaptureCallback { _, _, _ -> true }
367+
val nextHint = Hint()
368+
assertThat(processor.process(event, nextHint)).isSameInstanceAs(event)
369+
assertThat(nextHint.viewHierarchy).isNotNull()
370+
}
371+
345372
@Test
346373
fun `when capture callback returns true, a view hierarchy should be captured`() {
347374
fixture.options.setBeforeViewHierarchyCaptureCallback { _, _, _ -> true }

‎sentry-apollo-3/build.gradle.kts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ dependencies {
3333
testImplementation(kotlin(Config.kotlinStdLib))
3434
testImplementation(libs.apollo3.kotlin)
3535
testImplementation(libs.kotlin.test.junit)
36+
testImplementation(libs.google.truth)
3637
testImplementation(libs.kotlinx.coroutines)
3738
testImplementation(libs.mockito.kotlin)
3839
testImplementation(libs.mockito.inline)

‎sentry-apollo-3/src/main/java/io/sentry/apollo3/SentryApollo3HttpInterceptor.kt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,7 @@ constructor(
223223
span.spanContext.sampled = false
224224
}
225225
} catch (e: Throwable) {
226+
span.spanContext.sampled = false
226227
scopes.options.logger.log(
227228
SentryLevel.ERROR,
228229
"An error occurred while executing beforeSpan on ApolloInterceptor",

‎sentry-apollo-3/src/test/java/io/sentry/apollo3/SentryApollo3InterceptorTest.kt‎

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,15 @@ import com.apollographql.apollo3.exception.ApolloException
77
import com.apollographql.apollo3.exception.ApolloHttpException
88
import com.apollographql.apollo3.network.http.HttpInterceptor
99
import com.apollographql.apollo3.network.http.HttpInterceptorChain
10+
import com.google.common.truth.Truth.assertThat
1011
import io.sentry.BaggageHeader
1112
import io.sentry.Breadcrumb
13+
import io.sentry.ILogger
1214
import io.sentry.IScopes
1315
import io.sentry.ITransaction
1416
import io.sentry.Scope
1517
import io.sentry.ScopeCallback
18+
import io.sentry.SentryLevel
1619
import io.sentry.SentryOptions
1720
import io.sentry.SentryOptions.DEFAULT_PROPAGATION_TARGETS
1821
import io.sentry.SentryTraceHeader
@@ -303,16 +306,42 @@ class SentryApollo3InterceptorTest {
303306
}
304307

305308
@Test
306-
fun `when customizer throws, exception is handled`() {
307-
executeQuery(fixture.getSut(beforeSpan = { _, _, _ -> throw RuntimeException() }))
309+
fun `when beforeSpan throws, drops span and preserves response`(): Unit = runBlocking {
310+
val failure = IllegalStateException("callback failed")
311+
val logger = mock<ILogger>()
312+
fixture.options.isDebug = true
313+
fixture.options.setLogger(logger)
314+
val tx =
315+
SentryTracer(TransactionContext("op", "desc", TracesSamplingDecision(true)), fixture.scopes)
316+
whenever(fixture.scopes.span).thenReturn(tx)
317+
val sut =
318+
fixture.getSut(
319+
beforeSpan = { span, _, _ ->
320+
span.description = "partially modified"
321+
throw failure
322+
}
323+
)
308324

325+
val response = sut.query(LaunchDetailsQuery("83")).execute()
326+
assertThat(response.data).isNotNull()
327+
val span = tx.children.single()
328+
assertThat(span.isSampled).isFalse()
329+
assertThat(span.isFinished).isTrue()
330+
tx.finish()
309331
verify(fixture.scopes)
310332
.captureTransaction(
311-
check { assertEquals(1, it.spans.size) },
333+
check { assertThat(it.spans).isEmpty() },
312334
anyOrNull<TraceContext>(),
313335
anyOrNull(),
314336
anyOrNull(),
315337
)
338+
verify(fixture.scopes).addBreadcrumb(any<Breadcrumb>(), anyOrNull())
339+
verify(logger)
340+
.log(
341+
SentryLevel.ERROR,
342+
"An error occurred while executing beforeSpan on ApolloInterceptor",
343+
failure,
344+
)
316345
}
317346

318347
@Test

‎sentry-apollo-4/build.gradle.kts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ dependencies {
3333
testImplementation(kotlin(Config.kotlinStdLib))
3434
testImplementation(libs.apollo4.kotlin)
3535
testImplementation(libs.kotlin.test.junit)
36+
testImplementation(libs.google.truth)
3637
testImplementation(libs.kotlinx.coroutines)
3738
testImplementation(libs.kotlinx.coroutines.test)
3839
testImplementation(libs.mockito.kotlin)

‎sentry-apollo-4/src/main/java/io/sentry/apollo4/SentryApollo4HttpInterceptor.kt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,7 @@ constructor(
222222
span.spanContext.sampled = false
223223
}
224224
} catch (e: Throwable) {
225+
span.spanContext.sampled = false
225226
scopes.options.logger.log(
226227
SentryLevel.ERROR,
227228
"An error occurred while executing beforeSpan in ApolloInterceptor",

0 commit comments

Comments
 (0)