Get your mind around the second half of the if/else statement switching based around .IsSuccessStatusCode here which looks like this:
} else {
throw new Exception("Ouch!");
}
What if the exception which said "Ouch!" were to be thrown in the Web API controller at api/something and we wanted to capture the word "Ouch!" in the else half of our if/else. How would we do so? So far, I've only figured out how to do so with the code which follows which functionally does the same thing as the code above in that they both throw an "Ouch!" exception while the two approaches keep the "Ouch!" magic string in different locales. I mean to communicate that the message variable will end up with "Ouch!" inside of it assuming that the Web API controller at api/something throws an "Ouch!" exception exactly as the middlemost of three lines above does. Make sense? I'm starting to babble.
} else {
string exception = response.Content.ReadAsStringAsync().Result;
string message = exception.Split('"').ToArray()[7];
throw new Exception(message);
}
Doesn't splitting the exception variable and finding the eighth piece of it seem ghetto to you? Me too! This was the only way so far I have found to get "Ouch!" by itself. That isn't because there isn't another way. This is just all that I have tried so far. When I set a breakpoint in the application and look at what ends up in the exception variable, Visual Studio 2013 tells me that this is in there:
"{\"Message\":\"An error has occurred.\",\"ExceptionMessage\":\"Ouch!\",\"ExceptionType\":\"System.Exception\",\"StackTrace\":\" at MyNamespace.SomethingController.Post(SomeType someType) in c:\\\\source\\\\stuff\\\\Controllers\\\\MvcController.cs:line 23\\r\\n at lambda_method(Closure , Object , Object[] )\\r\\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.
I can probably cast this to a particular type in C#, but what type? I tried mapping it to an Exception type in the same way I map to the MyCustomType type in the link I provide above, but my efforts were to no avail. Here are some links that I found which were helpful, but only so helpful:
- http://stackoverflow.com/questions/12103946/httpclient-doesnt-report-exception-returned-from-web-api
- http://www.codeproject.com/Articles/611176/Calling-ASP-NET-WebAPI-using-HttpClient
Addendum 9/7/2014: I tried to beat this challenge a few more ways. I tried to deserialize to an Exception type without luck for example. In looking at the first of the two links above, I now wonder if something like the following would work. I dunno.
} else {
string exception = response.Content.ReadAsStringAsync().Result;
Exception trueException = new Exception(exception);
throw new Exception(trueException.Message);
}
I don't need to do this to throw an exception. That is a bad example. If I just want to elegantly get at what is at trueException.Message in the shape of a string how do I do so? That is the big question here.
No comments:
Post a Comment