5

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("")
}
asked Jan 2, 2014 at 22:26

2 Answers 2

10

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 
}
answered Jan 2, 2014 at 22:32
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that compiles. Something else doesn't work, but that is another problem ;)
3

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

answered Jan 2, 2014 at 22:29

1 Comment

Thanks again :) The solution of @tomas-petricek works better :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.