【问题标题】:What's the best way to handle asynchronous HttpWebRequest exceptions in C#?在 C# 中处理异步 HttpWebRequest 异常的最佳方法是什么?
【发布时间】:2011-05-25 23:39:33
【问题描述】:

我正在编写一些代码以异步使用 HttpWebRequest。如果你们中的任何人以前曾经这样做过,那么您就会知道错误处理可能会有点痛苦,因为如果在某个回调方法中抛出异常,则无法通过 try 将其传递回调用代码/catch 块。

我想要做的是通过将异常保存在传递给每个回调方法的状态对象中来处理错误。如果捕获到异常,状态对象将被更新,然后 http 调用将被中止。我遇到的问题是,在我的状态对象中,我必须使用 Exception 属性,以便可以存储任何类型的异常。当调用代码检查状态对象并“看到”一个异常时,它不知道它是什么类型的异常。

有没有办法让我的状态对象保存任何类型的异常,但仍保持异常为强类型?

状态对象

public class HttpPostClientAsyncModel
    {
        public HttpResponseSnapshot Response { get; set; }
        public HttpPostClientAsyncStatus Status { get; set; }
        public Exception Exception { get; set; }
        public WebRequest Request { get; set; }
    }

【问题讨论】:

  • 调用代码可以在 try 块中抛出 model.Exception,然后为调用者可以适当处理的特定 Exception 子类型设置捕获。或者也许不是...... :)
  • 这只是为了学习经验吗? HttpWebRequest.BeginGetResponse 怎么了?

标签: c# .net asynchronous httpwebrequest


【解决方案1】:

异常对象仍然是强类型并保留其原始字段值。您只需要像这样检查它:

if (asyncModel.Exception is ArgumentException)
{
  // Handle argument exception here
  string invalidParameter = (asyncModel.Exception as ArgumentException).ParamName;
}
else if (...)
{
}

无论如何,您通常都会使用 try/catch 块进行非常类似的检查,因此这应该不会带来不便。如果您真的对此感到担心,只需使用同步方法创建一个新线程并使用延续选项处理异常:

Task.Factory.StartNew(() => { DoWork(); })
.ContinueWith(t => Logger.Error("An exception occurred while processing. Check the inner exception for details", t.Exception),
TaskContinuationOptions.OnlyOnFaulted);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-29
    • 2013-10-13
    • 2021-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 2017-09-30
    相关资源
    最近更新 更多