简体   繁体   English

在 C# 中处理异步 HttpWebRequest 异常的最佳方法是什么?

[英]What's the best way to handle asynchronous HttpWebRequest exceptions in C#?

I am working on some code to use HttpWebRequest asynchronously.我正在编写一些代码以异步使用 HttpWebRequest。 If any of you have ever done this before, then you know that error handling can be a bit of a pain because if an exception is thrown in one of the callback methods, it can't be passed back to the calling code via a try/catch block.如果你们中的任何人以前曾经这样做过,那么您就会知道错误处理可能会有点痛苦,因为如果在某个回调方法中抛出异常,则无法通过 try 将其传递回调用代码/catch 块。

What I want to do is handle errors by saving exceptions in my state object that gets passed to each callback method.我想要做的是通过在传递给每个回调方法的 state object 中保存异常来处理错误。 If an exception is caught, the state object will be updated and then the http call will be aborted.如果捕获到异常,则 state object 将被更新,然后 http 调用将被中止。 The problem I have is that in my state object, I have to use an Exception property so that any type of exception can be stored.我遇到的问题是,在我的 state object 中,我必须使用 Exception 属性,以便可以存储任何类型的异常。 When the calling code checks the state object and "sees" an Exception, it doesn't know what type of exception it is.当调用代码检查 state object 并“看到”异常时,它不知道它是什么类型的异常。

Is there a way to allow my state object to hold any type of exception, but still keep the exception strongly-typed?有没有办法让我的 state object 保持任何类型的异常,但仍然保持异常强类型?

State Object State Object

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

The exception object is still strongly typed and retains its original field values.异常 object 仍然是强类型并保留其原始字段值。 All you need is to check it like this:您只需要像这样检查它:

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

You would normally do a very similar check with try/catch block anyway so this shouldn't be inconvenient.无论如何,您通常会使用 try/catch 块进行非常类似的检查,因此这应该不会带来不便。 If you're really worried about this, just create a new thread with the sync methods and handle the exception with continuation options:如果您真的担心这一点,只需使用同步方法创建一个新线程并使用延续选项处理异常:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM