Dart:尝试从使用"rethrow"的函数中捕获不捕获异常



我试图使用库livekit_client来创建一个聊天室,我试图处理连接失败时的异常,这是我用来连接和捕获错误的代码:

try {
room.connect(
'ws://localhost:7880',
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjEwNjcxMzA2NDgzLCJpc3MiOiJkZXZrZXkiLCJuYW1lIjoidXNlcjEiLCJuYmYiOjE2NzEzMDY0ODMsInN1YiI6InVzZXIxIiwidmlkZW8iOnsicm9vbSI6Im15LWZpcnN0LXJvb20iLCJyb29tSm9pbiI6dHJ1ZX19.SQ2OSWl1CG7UVbui_vmChfmUkYvT3QxKgXd9Yh167ws',
roomOptions: _roomOptions,
fastConnectOptions: FastConnectOptions(
microphone: const TrackOption(enabled: true),
camera: const TrackOption(enabled: true),
),
);
} catch (e) {
print('connection error $e');
}

但是异常没有被处理,相反,调试器停在库文件中的异常源处,特别是以下代码:

} catch (error) {
logger.fine('Connect Error $error');
_updateConnectionState(ConnectionState.disconnected);
rethrow;
}

停在'rethrow'行

所以'try catch'与使用'rethrow'的函数一起使用时有一些特定的限制?为什么它没有捕捉到异常?

完整测试代码:

import 'package:flutter/material.dart';
import 'package:livekit_client/livekit_client.dart';
import 'package:logging/logging.dart';
void main(List<String> args) {
Logger.root.level = Level.ALL; // defaults to Level.INFO
Logger.root.onRecord.listen((record) {
print('${record.level.name}: ${record.time}: ${record.message}');
});
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Room room = Room();
final RoomOptions _roomOptions = const RoomOptions(
adaptiveStream: true,
dynacast: true,
defaultVideoPublishOptions: VideoPublishOptions(
simulcast: true,
),
defaultScreenShareCaptureOptions:
ScreenShareCaptureOptions(useiOSBroadcastExtension: true),
);
@override
void initState() {
// TODO: implement initState
super.initState();
print('initializing');
try {
room.connect(
'ws://localhost:7880',
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjEwNjcxMzA2NDgzLCJpc3MiOiJkZXZrZXkiLCJuYW1lIjoidXNlcjEiLCJuYmYiOjE2NzEzMDY0ODMsInN1YiI6InVzZXIxIiwidmlkZW8iOnsicm9vbSI6Im15LWZpcnN0LXJvb20iLCJyb29tSm9pbiI6dHJ1ZX19.SQ2OSWl1CG7UVbui_vmChfmUkYvT3QxKgXd9Yh167ws',
roomOptions: _roomOptions,
fastConnectOptions: FastConnectOptions(
microphone: const TrackOption(enabled: true),
camera: const TrackOption(enabled: true),
),
);
} catch (e) {
print('connection error $e');
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(),
);
}
}

这只是一个猜测。但是room.connect()异步方法?它连接到一个在线服务器,所以它必须返回一个Future。尝试添加一个await关键字。另外,注意你不能在initState方法中写入async/await。所以也许可以尝试从main()方法连接到服务器,或者使用提供商。

你的代码应该看起来像这样:-

Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
try {
await room.connect();
} catch (error) {
// handle error.
}
runApp(MyApp());
}

最新更新