将来使用catchError捕获错误并抛出另一种类型 [英] Catch error using catchError in a future and throw another type
问题描述
我不确定这种错误处理和抽象是否以错误的方式完成。
I am not sure if this type of error handling and abstraction is done in a wrong way.
Future<void> _refresh() {
return Future(() => throw someError)
.catchError((error) {
// maybe do something here
throw abstractedError; //or even the same error
});
能够在另一个地方相应地使用它:
Being able in another place to use it accordingly:
// in a widget/another place
void doSomething() {
_refresh()
.then((_) => bla())
.catchError((error) {
//showSomeAlert() or handleSomething()
});
}
推荐答案
我们在flutter框架中catch函数的描述:
We have in the flutter framework the description for the catch function:
- 处理此[Future]发出的错误。
- 这是 catch块的异步等效项。
...
将来的catchError(Function onError,{bool test(Object error)});
在链接期货时,建议不要使用:
When chaining futures I would advise against of using:
throw error;
而是使用:
return Future.error(SecondError());
这是因为,如果您链接一个未来并期望使用catchError future来捕获错误,
This is because if you chain a future and expect to catch the error using the catchError future you will have the following problem.
Future<void> _refresh() {
return throw Exception("Exception");
}
void main() {
_refresh() // .then((_) => print("bla"))
.catchError(() => print("not able to be reached"));
}
您将收到错误未捕获的异常:异常:异常。
这与使用RX时的情况类似(通常),而不是扔掉,而是向您发送一条Sigle.error(或任何其他可观察到的错误) 。
This is similar when using RX (in general) and instead of throwing you send down the chain a Sigle.error (or any other observable with error).
TLDR:
使用期货并将它们链接起来(包括catchError)时,请使用 Future.error(Exception( Exception))处理错误。
When working with Futures and chaining them (including catchError) use Future.error(Exception("Exception")) to handle errors.
如果您正在使用投掷,请确保使用尝试抓或 Future(()-> throw ...)
If you are using throw make sure or surround with try catch or Future(() -> throw ... )
这篇关于将来使用catchError捕获错误并抛出另一种类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!