开发者

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

开发者 https://www.devze.com 2023-03-08 05:33 出处:网络
I am working on some code to use HttpWebRequest asynchronously.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 o

I am working on some code to use HttpWebRequest asynchronously. 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.

What I want to do is handle errors by saving exceptions in my state object that gets passed to each callback method. If an exception is caught, the state object will be updated and then the http call will be aborted. 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. When开发者_开发问答 the calling code checks the state object and "sees" an Exception, it doesn't know what type of exception it is.

Is there a way to allow my state object to hold any type of exception, but still keep the exception strongly-typed?

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. 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. 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);
0

精彩评论

暂无评论...
验证码 换一张
取 消