2015-09-27 179 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