Exception 异步抛出异常
我有以下代码:Exception 异步抛出异常,exception,f#,Exception,F#,我有以下代码: member public this.GetData(uri: string) = async { let! res = Async.AwaitTask(httpClient.GetAsync uri) return res } 当属性res.IsSuccessStatusCode为false时,我想抛出一个异常,我如何实现这一点。无法编译以下代码: member public this.GetData(uri: string) = async { le
member public this.GetData(uri: string) = async {
let! res = Async.AwaitTask(httpClient.GetAsync uri)
return res
}
当属性res.IsSuccessStatusCode
为false
时,我想抛出一个异常,我如何实现这一点。无法编译以下代码:
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("")
}
因此,第一部分是需要将
newexception()
用括号括起来,以确保F#正确解释代码
raise (new Exception(""))
也可以使用任一管道操作符
raise <| new Exception("")
new Exception |> raise
其次,您需要从两个分支返回,因此前缀
raise
带有return
您当然需要将新异常(…)
括在括号中,但在这种情况下这是不够的-match语句的两个分支都需要返回一个值,因此您还需要插入return
:
async {
let! res = Async.AwaitTask(httpClient.GetAsync uri)
match res.IsSuccessStatusCode with
| true -> return res
| false -> return raise (new Exception(""))
}
实际上,使用if
计算更容易编写,该计算可以包含返回单位的主体(如果操作未成功,则会引发异常),因此在这种情况下,您不需要return
:
async {
let! res = Async.AwaitTask(httpClient.GetAsync uri)
if not res.IsSuccessStatusCode then
raise (new Exception(""))
return res
}
谢谢,这就够了。其他东西不起作用,但这是另一个问题;)再次感谢:)tomas petricek的解决方案效果更好:)
async {
let! res = Async.AwaitTask(httpClient.GetAsync uri)
if not res.IsSuccessStatusCode then
raise (new Exception(""))
return res
}