|
16 | 16 |
|
17 | 17 | package za.co.absa.pramen.core.utils |
18 | 18 |
|
19 | | -import scala.util.control.NonFatal |
20 | | - |
21 | 19 | object UsingUtils { |
22 | 20 | /** |
23 | 21 | * Executes the given action with a resource that implements the AutoCloseable interface, ensuring |
24 | 22 | * proper closure of the resource. Any exception that occurs during the action or resource closure |
25 | | - * is handled appropriately, with suppressed exceptions added where relevant. Null resources are not supported. |
| 23 | + * is handled appropriately, with suppressed exceptions added where relevant. |
26 | 24 | * |
27 | 25 | * @param resource a lazily evaluated resource that implements AutoCloseable |
28 | 26 | * @param action a function to be executed using the provided resource |
29 | 27 | * @tparam T the type of the resource, which must extend AutoCloseable |
30 | 28 | * @throws Throwable if either the action or resource closure fails. If both fail, the action's exception |
31 | 29 | * is thrown with the closure's exception added as suppressed |
32 | 30 | */ |
33 | | - def using[T <: AutoCloseable,U](resource: => T)(action: T => U): U = { |
34 | | - var actionExceptionOpt: Option[Throwable] = None |
| 31 | + def using[T <: AutoCloseable, U](resource: => T)(action: T => U): U = { |
| 32 | + var actionException: Throwable = null |
35 | 33 | val openedResource = resource |
36 | 34 |
|
37 | 35 | try { |
38 | | - return action(openedResource) |
| 36 | + action(openedResource) |
39 | 37 | } catch { |
40 | | - case NonFatal(ex) => |
41 | | - actionExceptionOpt = Option(ex) |
| 38 | + case t: Throwable => |
| 39 | + actionException = t |
| 40 | + throw t |
42 | 41 | } finally |
43 | 42 | if (openedResource != null) { |
44 | 43 | try |
45 | 44 | openedResource.close() |
46 | 45 | catch { |
47 | | - case NonFatal(closeException) => |
48 | | - actionExceptionOpt match { |
49 | | - case Some(actionException) => |
50 | | - actionException.addSuppressed(closeException) |
51 | | - throw actionException |
52 | | - case None => |
53 | | - throw closeException |
| 46 | + case closeException: Throwable => |
| 47 | + if (actionException != null) { |
| 48 | + actionException.addSuppressed(closeException) |
| 49 | + } else { |
| 50 | + throw closeException |
54 | 51 | } |
55 | 52 | } |
56 | 53 | } |
57 | | - |
58 | | - // It is not possible to return a valid value of type U at this point so the rest of code should return Nothing |
59 | | - actionExceptionOpt match { |
60 | | - case Some(ex) => throw ex |
61 | | - case None => throw new IllegalArgumentException("Unreachable code") |
62 | | - } |
63 | 54 | } |
64 | 55 | } |
0 commit comments