I am seeing some strange behavior in my try/catch-rethrow code blocks.
I have a method which instantiates a class of ClientGet and gets the Result value from that class.
public Task<T> Get<T>(ClientRequest<T> Request)
{
try
{
return new ClientGet<T>(UpdateRequest(Request)).Result;
}
catch (Exception)
{
throw;
}
}
The ClientGet class looks like this:
public class ClientGet<T> : IClientAction<T>
{
public Task<T> Result { get; set; }
public ClientGet(ClientRequest<T> request)
{
try
{
Result = GetResult(request);
}
catch (Exception)
{
throw;
}
}
private async Task<T> GetResult(ClientRequest<T> request)
{
if (string.IsNullOrEmpty(request.FullPath))
{
throw new ApplicationException("You must specify a path in your request.");
}
try
{
using (HttpClient client = new HttpClient())
{
if (!string.IsNullOrEmpty(request.Settings.Token)) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", request.Settings.Token); }
var response = await client.GetAsync(request.FullPath);
if (response.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<T>(await response.Content.ReadAsStringAsync());
}
throw new HttpRequestException((int)response.StatusCode + ": " + response.ReasonPhrase);
}
}
catch (Exception)
{
throw;
}
}
}
If the response.IsSuccessStatusCode is false, for some reason the code stops at the catch of my GetResult method and posts it as an ASP.NET Unhandled Exception error on my throw; line. I have all of the re-throws so that the errors can be passed back up to the original caller at a higher level of the application.
Here is the exact message I get back:
401: Unauthorized Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.Http.HttpRequestException: 401: Unauthorized
Source Error:
Line 45: catch (Exception)
Line 46: {
Line 47: throw;
Line 48: }
Line 49: }
Not sure what you expect to happen. Sounds like the code is doing exactly what it should. If the condition is not satisified, it proceeds to new next line where you throw HttpRequestException
, since this is all wrapped in a try-catch, that exception is caught, and then re-thrown. However, this is the first time an exception is allowed to bubble up, so this is where Visual Studio will indicate the exception originated from. It will be eventually caught by the calling method's try-catch, and then finally raised to uncaught status after it's thrown again there.
However, you're breaking a fundamental rule of using try-catch here: only catch an exception if you intend on actually handling it. If all you're going to do is throw it in the catch block, then the entire try-catch is pointless. The default behavior is to allow it to bubble up through the stack; you don't have to throw it explicitly to accomplish that.