在ContinueWith块中抛出异常

时间:2016-09-12 10:26:58

标签: c# asynchronous

我正在使用HttpClient异步调用Web服务,并使用func myfunc1 (somedata string) { fmt.Println(somedata) } 处理响应。在此范围内,我想查看ContinueWith,如果它不是200(成功)则抛出异常。

我的代码如下:

HttpStatusCode

但是,在运行此操作而不是返回其中一个例外情况时,我已将其指定为由// Call the GetAddress service passing in the postcode var task = client.GetAsync(url) .ContinueWith((taskWithResponse) => { var response = taskWithResponse.Result; ValidateResponse(response.StatusCode); var jsonString = response.Content.ReadAsStringAsync(); jsonString.Wait(); model = JsonConvert.DeserializeObject<GetAddressResults>(jsonString.Result); }); task.Wait(); private static void ValidateResponse(HttpStatusCode statusCode) { Exception exception = null; switch(statusCode) { case HttpStatusCode.NotFound: exception = new NotFoundException(); break; case HttpStatusCode.BadRequest: exception = new InvalidException(); break; case HttpStatusCode.Forbidden: exception = new ForbiddenException(); break; case (System.Net.HttpStatusCode)429: exception = new ExceededLimitException(); break; default: return; } throw exception; } 抓住并抛出task.Wait()

有没有办法让任务抛出我最初想要的异常,或者我需要对AggregateException方法进行try / catch并拉出我的异常类型?

1 个答案:

答案 0 :(得分:2)

您正在同步调用 Web服务。请改为使用await / async个关键字:

try 
{
    var response = await client.GetAsync(url);
    ValidateResponse(response.StatusCode);
    var jsonString = await response.Content.ReadAsStringAsync();
    model = JsonConvert.DeserializeObject<GetAddressResults>(jsonString);
} 
catch (NotFoundException e) 
{
    // ...
}
catch (ForbiddenException e) 
{
    // ...
}
...

如果您无法使用这些关键字(可能在Visual Studio 2010中),请抓住AggregateException并检查它的InnerExceptions属性。