在异步操作中抛出异常

5

I have the following code:

member public this.GetData(uri: string) = async {
    let! res = Async.AwaitTask(httpClient.GetAsync uri)
    return res
}

当属性res.IsSuccessStatusCodefalse时,我想抛出一个异常,我该如何实现。以下代码无法编译:
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个回答

10

在这种情况下,您肯定需要将new Exception(...)放在括号中,但这还不足够-匹配语句的两个分支都需要返回一个值,因此您还需要插入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 
}

谢谢,编译通过了。还有其他问题,但那是另一个问题 ;) - Knerd

3
所以第一部分就是需要用括号将new Exception()包起来,以确保F#能够正确地解释代码。
raise (new Exception(""))

或者您可以使用任意一个管道操作符

raise <| new Exception("")
new Exception |> raise

或者你可以更改类型并使用failwith

failwith "some message"

其次,你需要从两个分支都返回,所以将raise前缀改为return

再次感谢 :) @tomas-petricek的解决方案更好 :) - Knerd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接