Skip to content

Commit 57f6ea3

Browse files
committed
added try catch to AndroidRuntimeManager.runWithRelaxedPolicy
1 parent b2e03d4 commit 57f6ea3

File tree

2 files changed

+37
-4
lines changed

2 files changed

+37
-4
lines changed

sentry-android-core/src/main/java/io/sentry/android/core/internal/util/AndroidRuntimeManager.java

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,11 @@ public <T> T runWithRelaxedPolicy(final @NotNull IRuntimeManagerCallback<T> toRu
1313
final @NotNull StrictMode.VmPolicy oldVmPolicy = StrictMode.getVmPolicy();
1414
StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.LAX);
1515
StrictMode.setVmPolicy(StrictMode.VmPolicy.LAX);
16-
final @NotNull T t = toRun.run();
17-
StrictMode.setThreadPolicy(oldPolicy);
18-
StrictMode.setVmPolicy(oldVmPolicy);
19-
return t;
16+
try {
17+
return toRun.run();
18+
} finally {
19+
StrictMode.setThreadPolicy(oldPolicy);
20+
StrictMode.setVmPolicy(oldVmPolicy);
21+
}
2022
}
2123
}

sentry-android-core/src/test/java/io/sentry/android/core/internal/util/AndroidRuntimeManagerTest.kt

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,4 +53,35 @@ class AndroidRuntimeManagerTest {
5353
// Ensure the code ran
5454
assertTrue(called)
5555
}
56+
57+
@Test
58+
fun `runWithRelaxedPolicy changes policy and restores it afterwards even if the code throws`() {
59+
var called = false
60+
val threadPolicy = StrictMode.ThreadPolicy.Builder().detectAll().penaltyDeath().build()
61+
val vmPolicy = StrictMode.VmPolicy.Builder().detectAll().penaltyDeath().build()
62+
63+
// Set and assert the StrictMode policies
64+
StrictMode.setThreadPolicy(threadPolicy)
65+
StrictMode.setVmPolicy(vmPolicy)
66+
67+
// Run the function and assert LAX policies
68+
try {
69+
sut.runWithRelaxedPolicy {
70+
assertEquals(
71+
StrictMode.ThreadPolicy.LAX.toString(),
72+
StrictMode.getThreadPolicy().toString(),
73+
)
74+
assertEquals(StrictMode.VmPolicy.LAX.toString(), StrictMode.getVmPolicy().toString())
75+
called = true
76+
throw Exception("Test exception")
77+
}
78+
} catch (_: Exception) {}
79+
80+
// Policies should be reverted back
81+
assertEquals(threadPolicy.toString(), StrictMode.getThreadPolicy().toString())
82+
assertEquals(vmPolicy.toString(), StrictMode.getVmPolicy().toString())
83+
84+
// Ensure the code ran
85+
assertTrue(called)
86+
}
5687
}

0 commit comments

Comments
 (0)