我不确定这种类型的错误处理和抽象是否以错误的方式完成。
Future<void> _refresh() {
return Future(() => throw someError)
.catchError((error) {
// maybe do something here
throw abstractedError; //or even the same error
});
能够在其他地方相应地使用它:
// in a widget/another place
void doSomething() {
_refresh()
.then((_) => bla())
.catchError((error) {
//showSomeAlert() or handleSomething()
});
}
最佳答案
您的解决方案应该可以工作(只需 throw
另一个异常),但更有表现力的方法可能是使用 Future.error
:
Future<void> someApi() {
return Future(() {
throw FirstError();
}).catchError((error, stackTrace) {
print("inner: $error");
// although `throw SecondError()` has the same effect.
return Future.error(SecondError());
});
}
然后使用
someApi()
.then((val) { print("success"); })
.catchError((error, stackTrace) {
// error is SecondError
print("outer: $error");
});
您可以在以下位置使用它:https://dartpad.dartlang.org/8fef76c5ba1c76a23042025097ed3e0a
关于android - 将来使用 catchError 捕获错误并抛出另一种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55596257/