Dur*_*rdu 4 android ios dart flutter
我不确定这种错误处理和抽象是否以错误的方式完成。
Future<void> _refresh() {
return Future(() => throw someError)
.catchError((error) {
// maybe do something here
throw abstractedError; //or even the same error
});
Run Code Online (Sandbox Code Playgroud)
能够在另一个地方相应地使用它:
// in a widget/another place
void doSomething() {
_refresh()
.then((_) => bla())
.catchError((error) {
//showSomeAlert() or handleSomething()
});
}
Run Code Online (Sandbox Code Playgroud)
Dur*_*rdu 15
我们在颤振框架中有 catch 函数的描述:
- 处理由此 [Future] 发出的错误。
- 这是“catch”块的异步等价物。... Future catchError(Function onError, {bool test(Object error)});
在链接期货时,我建议不要使用:
throw error;
Run Code Online (Sandbox Code Playgroud)
而是使用:
return Future.error(SecondError());
Run Code Online (Sandbox Code Playgroud)
这是因为如果您链接一个未来并希望使用 catchError 未来捕获错误,您将遇到以下问题。
Future<void> _refresh() {
return throw Exception("Exception");
}
void main() {
_refresh() // .then((_) => print("bla"))
.catchError(() => print("not able to be reached"));
}
Run Code Online (Sandbox Code Playgroud)
你会得到一个错误未捕获的异常:异常:异常。
这与使用 RX 时(一般情况下)类似,而不是向链下发送 Sigle.error (或任何其他可观察到的错误)。
域名注册地址:
当使用Futures并链接它们(包括 catchError)时,使用Future.error(Exception("Exception"))来处理错误。
如果您正在使用throw ,请确保或用try catch或Future(() -> throw ... )包围
您的解决方案应该可以工作(仅是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());
});
}
Run Code Online (Sandbox Code Playgroud)
然后使用
someApi()
.then((val) { print("success"); })
.catchError((error, stackTrace) {
// error is SecondError
print("outer: $error");
});
Run Code Online (Sandbox Code Playgroud)
您可以在以下位置使用它:https : //dartpad.dartlang.org/8fef76c5ba1c76a23042025097ed3e0a
| 归档时间: |
|
| 查看次数: |
2587 次 |
| 最近记录: |