Skip to content

Commit 4c06546

Browse files
committed
Add MiscUtility#handleException(supplier, throwables)
1 parent d954954 commit 4c06546

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

src/main/java/xyz/srnyx/javautilities/MiscUtility.java

+22-6
Original file line numberDiff line numberDiff line change
@@ -14,23 +14,39 @@
1414
*/
1515
public class MiscUtility {
1616
/**
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
1818
*
1919
* @param supplier the {@link Supplier} to execute
20+
* @param throwables the specific {@link Throwable}s to catch
2021
*
21-
* @return the result of the {@link Supplier} or {@code null}
22+
* @return the result of the {@link Supplier} or empty
2223
*
2324
* @param <R> the type of the result
2425
*/
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) {
2728
try {
2829
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;
3133
}
3234
}
3335

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+
3450
/**
3551
* Gets a {@link Set} of all the enum's value's names
3652
*

0 commit comments

Comments
 (0)