gpt4 book ai didi

c# - httpclient.GetStringAsync(url) 异步 api 调用的异常处理

转载 作者:太空宇宙 更新时间:2023-11-03 13:19:58 25 4
gpt4 key购买 nike

如果你有以下方法:

public async Task<string> GetTAsync(url)
{
return await httpClient.GetStringAsync(url);
}

public async Task<List<string>> Get(){
var task1 = GetTAsync(url1);
var task2 = GetTAsync(url2);
await Task.WhenAll(new Task[]{task1, task2});
// but this may through if any of the tasks fail.
//process both result
}

如何处理异常?我查看了 HttpClient.GetStringAsync(url) 方法的文档,它可能抛出的唯一异常似乎是 ArgumentNullException。但至少我遇到过一次禁止错误,并且想处理所有可能的异常。但我找不到任何具体的异常(exception)。我应该在这里捕获 Exception 异常吗?如果它更具体,我将不胜感激。请帮忙,它真的很重要。

最佳答案

最后我想通了:

public async Task<List<string>> Get()
{
var task1 = GetTAsync(url1);
var task2 = GetTAsync(url2);
var tasks = new List<Task>{task1, task2};
//instead of calling Task.WhenAll and wait until all of them finishes
//and which messes me up when one of them throws, i got the following code
//to process each as they complete and handle their exception (if they throw too)
foreach(var task in tasks)
{
try{
var result = await task; //this may throw so wrapping it in try catch block
//use result here
}
catch(Exception e) // I would appreciate if i get more specific exception but,
// even HttpRequestException as some indicates couldn't seem
// working so i am using more generic exception instead.
{
//deal with it
}
}
}

这是我终于想到的一个更好的解决方案。如果有更好的东西,我很想听听。我发布这个 - 以防其他人遇到同样的问题。

关于c# - httpclient.GetStringAsync(url) 异步 api 调用的异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24689263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com