无法捕获SocketException [英] Cannot catch SocketException

查看:594
本文介绍了无法捕获SocketException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试Dart,现在已经为此苦苦挣扎了很多。调用:

I am trying out Dart and I've been struggling with this for quite a bit now. Calling:

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

一次工作就像一种魅力。然后,尝试

Once works like a charm. And then, trying

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

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

Now I'd expect that if I were to use this try-catch and start listening to the same port more than once, because I'm catching ALL exceptions and ALL errors, the program wouldn't crash. However, after running the code twice, instead of entering any try/catch clause I get:


Uncaut错误:SocketException:无法创建服务器套接字(操作系统错误:通常只允许每个套接字地址(协议/网络地址/端口)使用一种。

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子句?

While I understand what the error is, I don't understand why doesn't it simply enter the catch Error/Exception clause?

推荐答案

异步使用 try / catch https://www.dartlang.org/docs/tutorials/futures/ ),除非您使用的是 async / 等待 https://www.dartlang.org/articles/await-async/

Asynchronous errors can't be caught using 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:// git hub.com/dart-lang/sdk/issues/24278


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

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

这篇关于无法捕获SocketException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆