f# - Catching HttpClient timeouts within an async workflow -
i'm calling httpclient via async.awaittask, being called within agent (mailboxprocessor). wanting catch errors during http call used try...with in async workflow, misses catching client-side timeout exceptions cause agent crash.
minimal reproduction:
#r "system.net.http" open system open system.net.http let client = new httpclient() client.timeout <- timespan.fromseconds(1.) async { try let! content = async.awaittask <| client.getstringasync("http://fake-response.appspot.com/?sleep=30") return content ex -> // not catch client-side timeout exception return "caught it!" } |> async.runsynchronously // throws system.operationcanceledexception: operation canceled i can fix making syncronous, prefer keep whole stack async might running lot of these in parallel:
#r "system.net.http" open system open system.net.http let client = new httpclient() client.timeout <- timespan.fromseconds(1.) try async.awaittask <| client.getstringasync("http://fake-response.appspot.com/?sleep=30") |> async.runsynchronously ex -> "caught it!" // returns "caught it!" is there effective way of catching operationcanceledexception within async context?
this happens because httpclient.getstringasync task cancelled, instead of failing timeoutexception, prompting async mechanism fire cancellation continuations, cannot handled. simple way solve problem following:
async { try let! content = client.getstringasync("http://fake-response.appspot.com/?sleep=30") .continuewith(fun (t:task<string>) -> t.result) |> async.awaittask return content ex -> // not catch client-side timeout exception return "caught it!" }
Comments
Post a Comment