Fill and exception filters inside the F # `try`-`with` block

I am trying to convert this piece of C # to F #:

var webClient = new WebClient();
try {
    webClient.DownloadString (url);
} catch (WebException e) {
    var response = e.Response as HttpWebResponse;
    if (response == null)
        throw;
    using (response) {
        using (Stream data = response.GetResponseStream ()) {
            string text = new StreamReader (data).ReadToEnd ();
            throw new Exception (response.StatusCode + ": " + text);
        }
    }
}

I have already met this, but it does not compile, because I cannot use leteither useinside a block with , apparently:

let Download(url: string) =
    use webClient = new WebClient ()
    try
        webClient.DownloadString(url)
    with
        | :? WebException as ex when ex.Response :? HttpWebResponse ->
             use response = ex.Response :?> HttpWebResponse
             use data = response.GetResponseStream()
             let text = new StreamReader (data).ReadToEnd ()
             failwith response.StatusCode + ": " + text
+4
source share
1 answer

A little bit about splitting and using parentheses will help you a lot here:

let download (url : string) = 
    use webClient = new WebClient()
    try
        webClient.DownloadString(url)
    with
        | :? WebException as ex when (ex.Response :? HttpWebResponse) ->
             use response = ex.Response :?> HttpWebResponse
             use data = response.GetResponseStream()
             use reader = new StreamReader(data)
             let text = reader.ReadToEnd()
             failwith (response.StatusCode.ToString() + ": " + text)

This function compiles and works as expected.

, , , when ( , when it), .

failwith, , .

+7

All Articles