gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 07:25:51 30 4
gpt4 key购买 nike

我使用许多 api 与服务器通信,并希望处理来自此调用的意外异常。但是,它根本无法捕获异常。如何处理?

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

最佳答案

如果您使用像 Future 这样的异步方法,您可以使用 catchError 来处理 guide 中提到的异常.

这是您可以在 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}');
}
}

关于exception - 如何在 flutter 中捕获异步函数的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54687944/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com