2015-09-27 224 views
1

我正在尝试使用Dart,并且现在我一直在为此奋斗。打电话:无法捕捉SocketException

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.

虽然我知道是什么错误,我不明白为何它没有简单地输入捕获错误/异常条款?

回答

1

异步错误不能使用try/catchhttps://www.dartlang.org/docs/tutorials/futures/),除非你正在使用async/awaithttps://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'); 
    } 
} 
+0

我明白你的意思被抓,但我不明白为什么这是一个异步错误。我的意思是,在开始实际异步地收听请求之前,您会收到此错误,对吗? – Alexandr

+0

'HttpServer.bind()'已经是异步的(返回'Future ') –

+0

你是对的,Gunter。这次真是万分感谢! – Alexandr