2010-12-11 17 views
0

我已經寫了一個函數,在F#中給出url和WebClient對象的情況下啓動下載。然而,當我寫我的嘗試..與聲明是給我的錯誤「不完整的結構構造在表達或此點之前」。使用WebClient對象進行異常處理

let urlDownload(url:string, webClient:WebClient) = 
async { 
    try 
     let uri = new Uri(url) 
     /// References for progress queries 
     let contentLength = ref 0L 
     let bytesReceived = ref 0L 
     /// Updates progress statistics as progress is made 
     webClient.DownloadProgressChanged.Add(
      fun args -> 
       if !contentLength = 0L && webClient.ResponseHeaders.Get "Content-Length" <> null then 
        contentLength := webClient.ResponseHeaders.Get "Content-Length" |> Int64.Parse 
       bytesReceived := !bytesReceived + args.BytesReceived 
     ) 
     let! html = webClient.AsyncDownloadString(uri) 
    with 
     | :? UriFormatException -> printfn "Invalid URL" 
} 

它是基於斷碼的從MSDN here

什麼是真正奇怪的是,如果我把「printfn‘’」前有塊項目順利完成編譯。但是,當我運行它時,它會拋出一個UriFormatException異常,它被認爲是被with塊捕獲的。

回答

1

正如Brian所說的,問題在於,您將以let!結束塊(嘗試的主體),但使用綁定結束表達式是沒有任何意義的。據推測,你希望你的函數實際上返回的HTML,所以你應該做的:

let! html = webClient.AsyncDownloadString(uri) 
return html 

或等價,只是return! webClient.AsyncDownloadString(uri)

1

什麼是真正奇怪的是,如果我把 「printfn‘’」前有塊 項目編譯沒有錯誤。

這是預期的。 A let!不能是async塊的最後一行,就像let不能是正常塊的最後一行一樣。 (回想一下,

let x = 42 
blah(x) 

是 '速記' 爲表達

let x = 42 in blah(x) 

我想我不相信你關於UriFormatException。 :)