mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-04-19 03:01:48 +08:00
!890 【6.x】将Opt的ofTry捕获范围从Exception提升到Throwable
Merge pull request !890 from Cizai/v6-dev
This commit is contained in:
commit
6b14f57e33
@ -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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -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)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user