我在 try/catch-rethrow 代码块中看到了一些奇怪的行为。
我有一个方法可以实例化一个 ClientGet 类并从该类中获取 Result 值。
public Task<T> Get<T>(ClientRequest<T> Request)
{
try
{
return new ClientGet<T>(UpdateRequest(Request)).Result;
}
catch (Exception)
{
throw;
}
}
ClientGet 类如下所示:
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;
}
}
}
如果 response.IsSuccessStatusCode 为 false,由于某种原因,代码在我的 GetResult 方法的捕获处停止,并将其作为 ASP.NET Unhandled Exception 错误发布在我的 throw 上;线。我有所有的重新抛出,以便可以将错误传递回应用程序更高级别的原始调用者。
这是我得到的确切信息:
401: Unauthorized 说明:在执行当前的 Web 请求期间发生了未经处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。
异常详细信息:System.Net.Http.HttpRequestException:401:未经授权
源错误:
Line 45: catch (Exception)
Line 46: {
Line 47: throw;
Line 48: }
Line 49: }