HttpContentExtensions.ReadAsAsync methods throw instead of returning a faulted Task

Topics: ASP.NET Web API
Jan 29, 2013 at 3:35 PM

HttpContentExtensions.ReadAsAsync extension methods for HttpContent inside the System.Net.Http.Formatting project directly throws instead of returning a faulted Task.

Is there any specific reason for that?

Coordinator
Jan 29, 2013 at 8:10 PM

The thrown exception should get automatically turned into a faulted Task.

Daniel Roth

Jan 29, 2013 at 8:21 PM

Hi,

Thanks for the response.

Nope, not currently. It directly throws w/o returning a faulted Task. It's especially a pain on .NET 4.0. This is what I ended up because of this:

https://github.com/WebAPIDoodle/WebAPIDoodle/blob/dev/src/WebApiDoodle.Net.Http.Client/HttpResponseMessageExtensions.cs#L129-L143

It doesn't matter that much if you are using async/await as you would typically put a try/catch around it.

Jan 29, 2013 at 8:33 PM

Hi Tugberk,

This is by design. Any method that returns Task can throw ArgumentExceptions synchronously according to TAP guidelines.

http://msdn.microsoft.com/en-us/library/hh873175.aspx

The caller is responsible to check before calling the method.

Let me know if that clarifies.

Jan 29, 2013 at 8:59 PM

Hi HongmeiG,

Thanks for the response.

Yes, that part is the one that I agree but ReadAsync methods also throw InvalidOperationException if there is no formatter found to deserialize the content value: https://github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Net.Http.Formatting/HttpContentExtensions.cs#L137-L141 Sorry that this is the GitHub mirror for the aspnetwebstack project. I couldn't find a way to reference line numbers in CodePlex.

Is this something that should be done this way? Or would that make a better API to return a faulted Task there in such a case?

Thanks.

Jan 30, 2013 at 5:24 PM

Hi Tugberk,

InvalidOperationException is just like ArgumentException, both are indicating some form of user errors. The difference between those two exception types are somewhat subtle. InvalidOperationException generally relies on the state of the object while ArgumentException does not. For example, an ArgumentException should be thrown if the input is plain wrong, such as null. You can read more about that from http://msdn.microsoft.com/en-us/library/system.invalidoperationexception(v=vs.71).aspx

Based on the TAP guidelines, we should throw the exception synchronously if it is user error. Hope this clarifies.

Hongmei

Jan 30, 2013 at 5:28 PM

Hi Hongmei,

Thanks for the clarification and taking the time to respond.

Tugberk