【问题标题】:Cannot catch SocketException无法捕获 SocketException
【发布时间】:2020-04-23 23:00:03
【问题描述】:

我正在尝试 Dart,我已经为此苦苦挣扎了一段时间。调用:

runServer() {
  HttpServer.bind(InternetAddress.ANY_IP_V4, 8080)
  .then((server) {
    server.listen((HttpRequest request) {
      request.response.write('Hello, World!');
      request.response.close();
    });
  });
}

Once 就像一个魅力。然后,尝试

try {
    runServer();
} on Error catch (e) {
    print("error");
} on Exception catch(f) {
    print("exception");
}

现在我希望如果我使用这个 try-catch 并开始不止一次地监听同一个端口,因为我正在捕获所有异常和所有错误,程序不会崩溃。但是,在运行代码两次后,我没有输入任何 try/catch 子句:

Uncaut Error: SocketException: Failed to create server socket (OS Error: 每个套接字地址(协议/网络地址/端口)通常只允许使用一次。

虽然我明白错误是什么,但我不明白为什么不简单地进入 catch Error/Exception 子句?

【问题讨论】:

    标签: sockets exception dart socketexception


    【解决方案1】:

    除非您使用async/await (https://www.dartlang.org/articles/await-async/),否则至少不能使用try/catch (https://www.dartlang.org/docs/tutorials/futures/) 捕获异步错误

    另见https://github.com/dart-lang/sdk/issues/24278

    您可以在WebSocket 对象上使用done 未来来获取该错误,例如:

    import 'dart:async';
    import 'dart:io';
    
    main() async {
      // Connect to a web socket.
      WebSocket socket = await WebSocket.connect('ws://echo.websocket.org');
    
      // Setup listening.
      socket.listen((message) {
        print('message: $message');
      }, onError: (error) {
        print('error: $error');
      }, onDone: () {
        print('socket closed.');
      }, cancelOnError: true);
    
      // Add message, and then an error.
      socket.add('echo!');
      socket.addError(new Exception('error!'));
    
      // Wait for the socket to close.
      try {
        await socket.done;
        print('WebSocket donw');
      } catch (error) {
        print('WebScoket done with error $error');
      }
    }
    

    【讨论】:

    • 我明白你的意思,但我不明白为什么这是一个异步错误。我的意思是,在开始实际异步侦听请求之前,您会收到此错误,对吧?
    • HttpServer.bind() 已经是异步的(返回 Future<HttpServer>
    猜你喜欢
    • 2021-08-15
    • 2019-12-30
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-08
    • 2012-11-09
    相关资源
    最近更新 更多