Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion core/src/main/scala/ox/resource.scala
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,20 @@ inline def use[R, T](inline acquire: R, inline release: R => Unit)(inline f: R =
*/
inline def useInterruptible[R, T](inline acquire: R, inline release: R => Unit)(inline f: R => T): T =
val r = acquire
var caught: Throwable = null
try f(r)
finally release(r)
catch
case e: Throwable =>
caught = e
null.asInstanceOf[T]
finally
if caught == null then release(r)
else
try release(r)
catch case e: Throwable => caught.addSuppressed(e)
finally throw caught
end try
end useInterruptible

/** Use the given [[AutoCloseable]] resource, acquired using `acquire` in the given `f` code block. Releasing is [[uninterruptible]]. To use
* multiple resources, consider creating a [[supervised]] scope and [[useCloseableInScope]] method.
Expand Down
19 changes: 19 additions & 0 deletions core/src/test/scala/ox/ResourceTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -143,4 +143,23 @@ class ResourceTest extends AnyFlatSpec with Matchers:

trail.get shouldBe Vector("allocate", "in scope", "release")
}

it should "add suppressed exception when there's an exception during releasing" in {
val trail = Trail()

class TestResource:
trail.add("allocate")
def release(): Unit =
trail.add("release")
throw new RuntimeException("e1")

try
use(new TestResource, _.release()) { r =>
trail.add("in scope")
throw new RuntimeException("e2")
}
catch case e => trail.add(s"exception ${e.getMessage} (${e.getSuppressed.map(_.getMessage).mkString(", ")})")

trail.get shouldBe Vector("allocate", "in scope", "release", "exception e2 (e1)")
}
end ResourceTest