flutter - 如何在 Dart(Flutter)的回调函数中捕获异常?
问题描述
我在MyWebSocket
课堂上使用 WebSocket 变量。对于听我给出一个回调函数作为参数。如果此回调函数在调用类时抛出异常MyChat
,那么我无法在任何地方捕获该异常。
我的简化代码是:
class MyWebSocket {
WebSocket _ws;
...
// initialized in controller: _ws = WebSocket.connect(_some_url_);
// everything works (connect, listen)
...
void listen({void Function(dynamic) myOnListen}) {
try {
_ws.listen(myOnListen)
.onError((e) => print("MyWebSocket in MyChat.onError: $e"));
} catch (e) {
print("Catched in MyWebSocket: $e");
}
}
}
class MyChat {
MyWebSocket _chatWs = MyWebSocket();
...
void initWS() {
try {
_chatWs.listen(myOnListen: processMsg);
} catch (e) {
print("Catched in MyChat: $e");
}
}
void processMsg(dynamic msg) {
if(_some_stuff_like_invalid_msg_or_not_logged_in_...)
throw Exception("There is my Exception");
}
}
我已经try-catch
在每个可能的地方建立了捕获异常 - 没有成功,我只有未处理的异常:
E/flutter: [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] 未处理的异常:异常:有我的异常
E/颤振:#0 MyChat.processMsg
解决方案
请注意,您不能将传递的侦听器用作以后删除的键。为此,您可以在调用 listen() 时传递在 MyWebSocket 类中创建的新侦听器,然后使用此键删除侦听器。
class MyWebSocket {
WebSocket _ws;
void listen({void Function(dynamic) myOnListen, void Function(Error) onError}) {
try {
_ws.listen((){
try {
myOnListen({"label": "DATA"});
} catch (e) {
if(onError is Function)
onError(e)
}
})
.onError(onError);
} catch (e) {
print("Catched in MyWebSocket: $e");
}
}
}
class MyChat {
MyWebSocket _chatWs = MyWebSocket();
void initWS() {
try {
_chatWs.listen(myOnListen: processMsg, onError: (Error error){
print("ERROR: "+error.toString());
});
} catch (e) {
print("Catched in MyChat: $e");
}
}
void processMsg(dynamic msg) {
if(_some_stuff_like_invalid_msg_or_not_logged_in_...)
throw Exception("There is my Exception");
}
}