Skip to content

Commit 4ac94b6

Browse files
committed
enhance tapFailure scala docs add test for fatal exception propagation
1 parent 0848475 commit 4ac94b6

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

core/src/main/scala/com/avsystem/commons/SharedExtensions.scala

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -463,9 +463,13 @@ object SharedExtensionsUtils extends SharedExtensions {
463463
if (tr.isFailure) OptArg.Empty else OptArg(tr.get)
464464

465465
/**
466-
* Apply side-effect only if Try is a failure.
466+
* Apply side-effect only if Try is a failure. The provided `action` function will be called with the
467+
* throwable from the failure case, allowing you to perform operations like logging or error handling.
468+
*
469+
* Any exceptions thrown by the `action` function are caught and ignored, ensuring that this method
470+
* always returns the original Try instance regardless of what happens in the action.
467471
*
468-
* Don't use .failed projection here, because it unnecessarily creates Exception in case of Success,
472+
* Don't use .failed projection, because it unnecessarily creates Exception in case of Success,
469473
* which is an expensive operation.
470474
*/
471475
def tapFailure(action: Throwable => Unit): Try[A] = tr match {

core/src/test/scala/com/avsystem/commons/misc/SharedExtensionsTest.scala

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,4 +235,16 @@ class SharedExtensionsTest extends AnyFunSuite with Matchers {
235235

236236
assert(result === failureTry, "Original Failure should be returned even if action throws")
237237
}
238+
239+
test("Try.tapFailure - Fatal exception in action") {
240+
val originalException = new RuntimeException("original exception")
241+
val fatalException = new OutOfMemoryError("fatal exception")
242+
val failureTry = Failure(originalException)
243+
244+
val thrown = intercept[OutOfMemoryError] {
245+
failureTry.tapFailure(_ => throw fatalException)
246+
}
247+
248+
assert(thrown === fatalException, "Fatal exception should propagate out of tapFailure")
249+
}
238250
}

0 commit comments

Comments
 (0)