I have the following code:
member public this.GetData(uri: string) = async {
let! res = Async.AwaitTask(httpClient.GetAsync uri)
return res
}
When the property res.IsSuccessStatusCode is false I would like to throw an exception, how can I achieve this. The following code won't compile:
member public this.GetData(uri: string) = async {
let! res = Async.AwaitTask(httpClient.GetAsync uri)
match res.IsSuccessStatusCode with
| true -> return res
| false -> raise new Exception("")
}
2 Answers 2
You certainly need to wrap new Exception(...) in brackets, but that is not sufficient in this case - both branches of the match statement need to return a value, so you also need to insert return:
async {
let! res = Async.AwaitTask(httpClient.GetAsync uri)
match res.IsSuccessStatusCode with
| true -> return res
| false -> return raise (new Exception(""))
}
This is actually easier to write using an if computation which can contain body that returns unit (and throws an exception if the operation did not succeed) - and so you do not need return in that case:
async {
let! res = Async.AwaitTask(httpClient.GetAsync uri)
if not res.IsSuccessStatusCode then
raise (new Exception(""))
return res
}
1 Comment
So the first part is that you need to wrap the new Exception() with brackets to make sure that F# interprets the code correctly.
raise (new Exception(""))
or you can use either of the pipe operators
raise <| new Exception("")
new Exception |> raise
or you can change the type and use failwith
failwith "some message"
Secondly, you need to return from both branches, so prefix raise with return