将来使用catchError捕获错误并抛出另一种类型 [英] Catch error using catchError in a future and throw another type

查看:413
本文介绍了将来使用catchError捕获错误并抛出另一种类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定这种错误处理和抽象是否以错误的方式完成。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆