|
14 | 14 | */
|
15 | 15 | public class MiscUtility {
|
16 | 16 | /**
|
17 |
| - * If an exception is thrown by the {@link Supplier}, {@code null} is returned |
| 17 | + * If specific throwables are thrown by the {@link Supplier}, {@code null} is returned |
18 | 18 | *
|
19 | 19 | * @param supplier the {@link Supplier} to execute
|
| 20 | + * @param throwables the specific {@link Throwable}s to catch |
20 | 21 | *
|
21 |
| - * @return the result of the {@link Supplier} or {@code null} |
| 22 | + * @return the result of the {@link Supplier} or empty |
22 | 23 | *
|
23 | 24 | * @param <R> the type of the result
|
24 | 25 | */
|
25 |
| - @NotNull |
26 |
| - public static <R> Optional<R> handleException(@NotNull Supplier<R> supplier) { |
| 26 | + @NotNull @SafeVarargs |
| 27 | + public static <R> Optional<R> handleException(@NotNull Supplier<R> supplier, @NotNull Class<? extends Throwable>... throwables) { |
27 | 28 | try {
|
28 | 29 | return Optional.ofNullable(supplier.get());
|
29 |
| - } catch (final Exception ignored) { |
30 |
| - return Optional.empty(); |
| 30 | + } catch (final Exception e) { |
| 31 | + for (final Class<? extends Throwable> throwable : throwables) if (throwable.isInstance(e)) return Optional.empty(); |
| 32 | + throw e; |
31 | 33 | }
|
32 | 34 | }
|
33 | 35 |
|
| 36 | + /** |
| 37 | + * If an {@link Exception} is thrown by the {@link Supplier}, {@code null} is returned |
| 38 | + * |
| 39 | + * @param supplier the {@link Supplier} to execute |
| 40 | + * |
| 41 | + * @return the result of the {@link Supplier} or empty |
| 42 | + * |
| 43 | + * @param <R> the type of the result |
| 44 | + */ |
| 45 | + @NotNull |
| 46 | + public static <R> Optional<R> handleException(@NotNull Supplier<R> supplier) { |
| 47 | + return handleException(supplier, Exception.class); |
| 48 | + } |
| 49 | + |
34 | 50 | /**
|
35 | 51 | * Gets a {@link Set} of all the enum's value's names
|
36 | 52 | *
|
|
0 commit comments