无法捕获 SocketException

Cannot catch SocketException

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

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

一旦工作就像一个魅力。然后,尝试

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: Only one usage of each socket address (protocol/network address/port) is normally permitted.

虽然我明白错误是什么,但我不明白为什么它不直接输入 catch Error/Exception 子句?

无法使用 try/catch (https://www.dartlang.org/docs/tutorials/futures/) at least unless you are using async/await (https://www.dartlang.org/articles/await-async/)

捕获异步错误

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

You can use the done future on the WebSocket object to get that error, e.g.:

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');
  }
}