简体   繁体   English

如何在flutter中捕获异步函数的异常?

[英]How to catch exception of asynchronous function in flutter?

I uses many apis to communicate with server and want to handle unexpected exception from this callings.我使用许多 api 与服务器进行通信,并希望处理来自此调用的意外异常。 But, It cannot catch exception at all.但是,它根本无法捕获异常。 How to handle this?如何处理?

if(event is RandomChatEventMatchStart){
  yield RandomChatState.loading();
  try {
    chatRoomID = await _api.getRoomID();
    if(chatRoomID.isEmpty){
      chatRoomID = await _api.makeChatRoom();
      yield RandomChatState.madeChatRoom(chatRoomID);
    } else {
      await _api.enterChatRoom(chatRoomID);
      yield RandomChatState.matchSucceeded();
    }
  } catch(exception) {
    yield RandomChatState.apiFailed(exception.toString());
  }
}
E/flutter (12376): PlatformException(error, Invalid document reference. Document references must have an even number of segments, but messages has 1, null) E/flutter (12376): #0      StandardMethodCodec.decodeEnvelope  package:flutter/…/services/message_codecs.dart:564 E/flutter (12376):
#1      MethodChannel.invokeMethod  package:flutter/…/services/platform_channel.dart:292 E/flutter (12376): <asynchronous suspension> E/flutter (12376): #2      DocumentReference.snapshots.<anonymous closure>  ..\…\src\document_reference.dart:126 E/flutter (12376): #3     
_runGuarded (dart:async/stream_controller.dart:805:24) E/flutter (12376): #4      _BroadcastStreamController._subscribe (dart:async/broadcast_stream_controller.dart:213:7) E/flutter (12376):
#5      _ControllerStream._createSubscription (dart:async/stream_controller.dart:818:19) E/flutter (12376): #6     
_StreamImpl.listen (dart:async/stream_impl.dart:472:9) E/flutter (12376): #7      _StreamBuilderBaseState._subscribe  package:flutter/…/widgets/async.dart:135 E/flutter (12376): #8     
_StreamBuilderBaseState.didUpdateWidget  package:flutter/…/widgets/async.dart:120 E/flutter (12376): #9      StatefulElement.update  package:flutter/…/widgets/framework.dart:3863 E/flutter (12376): #10     Element.updateChild

If you're using async methods like Future , you can use catchError to handle the Exception as mentioned in this guide .如果您使用Future类的异步方法,则可以使用catchError来处理本指南中提到的异常。

Here's a sample that you can run on dartpad这是您可以在dartpad 上运行的示例

void main() {
  foo()
      .whenComplete(() => print('Completed'))
      .catchError((error) => print('Error $error'));
}

Future<void> foo() async {
  for (int i = 0; i < 5; i++) {
    if(i==4) throw Exception;
    print('hello ${i + 1}');
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM