!890 【6.x】将Opt的ofTry捕获范围从Exception提升到Throwable

Merge pull request !890 from Cizai/v6-dev
This commit is contained in:
Looly 2022-12-11 05:41:17 +00:00 committed by Gitee
commit 6b14f57e33
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
2 changed files with 14 additions and 8 deletions

View File

@ -32,6 +32,7 @@ import java.util.Objects;
import java.util.Optional;
import java.util.Collection;
import java.util.NoSuchElementException;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
@ -44,6 +45,7 @@ import java.util.stream.Stream;
*
* @param <T> 包裹里元素的类型
* @author VampireAchao
* @author Cizai
* @see java.util.Optional
*/
public class Opt<T> {
@ -119,9 +121,9 @@ public class Opt<T> {
public static <T> Opt<T> ofTry(final SerSupplier<T> supplier) {
try {
return Opt.ofNullable(supplier.getting());
} catch (final Exception e) {
} catch (final Throwable e) {
final Opt<T> empty = new Opt<>(null);
empty.exception = e;
empty.throwable = e;
return empty;
}
}
@ -143,7 +145,7 @@ public class Opt<T> {
* 包裹里实际的元素
*/
private final T value;
private Exception exception;
private Throwable throwable;
/**
* {@code Opt}的构造函数
@ -186,8 +188,8 @@ public class Opt<T> {
* @return 异常
* @since 5.7.17
*/
public Exception getException() {
return this.exception;
public Throwable getThrowable() {
return this.throwable;
}
/**
@ -198,7 +200,7 @@ public class Opt<T> {
* @since 5.7.17
*/
public boolean isFail() {
return null != this.exception;
return null != this.throwable;
}
/**

View File

@ -171,6 +171,10 @@ public class OptTest {
// 你可以在里面写一长串调用链 list.get(0).getUser().getId()
return list.get(0);
}).exceptionOrElse("hutool");
Assert.assertTrue(Opt.ofTry(() -> {
throw new AssertionError("");
}).getThrowable() instanceof AssertionError);
Assert.assertEquals(npe, npeSituation);
Assert.assertEquals(indexOut, indexOutSituation);
Assert.assertEquals("hutool", npe);
@ -186,8 +190,8 @@ public class OptTest {
}
});
Assert.assertTrue(
(i % 2 == 0 && opt.getException() instanceof IllegalStateException) ||
(i % 2 != 0 && opt.getException() instanceof NullPointerException)
(i % 2 == 0 && opt.getThrowable() instanceof IllegalStateException) ||
(i % 2 != 0 && opt.getThrowable() instanceof NullPointerException)
);
});
}