【发布时间】:2018-03-12 23:27:38
【问题描述】:
我有asp.net core 2.1 和HangFire 1.6.17 的应用程序。 HangFire 被配置为以特定间隔执行后台作业。后台作业使用 HttpClient 调用外部 API。如果 http 调用失败,则该方法会抛出带有元数据的自定义异常。想法是 hangfire 将使用元数据记录异常。我跟着best-practices-for-exceptions 创建异常
public class MyHttpRequestException : Exception
{
public string Content { get; private set; }
public string RequestUri { get; private set; }
public string HttpResponse { get; private set; }
public MyHttpRequestException()
{
}
public MyHttpRequestException(string message)
: base(message)
{
}
public MyHttpRequestException(string message, Exception innerException)
: base(message, innerException)
{
}
public MyHttpRequestException(string message, string content, string httpResponse, string requestUri)
: base(message)
{
Content = content;
RequestUri = requestUri;
HttpResponse = httpResponse;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append(base.ToString());
sb.AppendLine();
sb.AppendLine();
sb.AppendLine("Content");
sb.AppendLine(Content);
sb.AppendLine("RequestUri");
sb.AppendLine(RequestUri);
sb.AppendLine("HttpResponse");
sb.AppendLine(this.HttpResponse);
return sb.ToString();
}
}
我还有HttpResponseMessage 的扩展方法,确保API 请求成功,如果不成功则抛出MyHttpRequestException
public static class HttpResponseMessageExtensions
{
public static async Task EnsureSuccessStatusCodeAsync(this HttpResponseMessage response)
{
if (response.IsSuccessStatusCode)
{
return;
}
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var httpResponse = response.ToString();
var requestUri = response.RequestMessage.RequestUri.ToString()
if (response.Content != null)
response.Content.Dispose();
throw new MyHttpRequestException("Error while making http request.", content, httpResponse, requestUri);
}
}
这是我的后台作业,由 Hangfire 循环作业调度程序调用
public async Task DoSomething(string url)
{
var response = await _httpClient.GetAsync(url)
await response.EnsureSuccessStatusCodeAsync();
// do something here if everything is okay
}
问题
当EnsureSuccessStatusCodeAsync 方法抛出MyHttpRequestException 时,Hangfire 按预期记录异常,我在 HangFire 的仪表板中看到了这一点。然而 Hangfire 只记录异常消息和堆栈跟踪。 我没有看到我的自定义属性被记录(即 Content、RequestUri、HttpResponse)
在 clssic .NET 中,我们像这样使用 SerializationInfo SO post
如何在 .NET Core 中创建自定义异常,以便记录元数据?
注意:
当MyHttpRequestException 被抛出时,我注意到异常的 ToString() 方法被调用
但是,我看不到任何 ToString() 返回的内容都被 Hangfire 记录下来。
我不知道这是否是挂火问题,或者我需要以不同的方式实现 MyHttpRequestException。
【问题讨论】:
标签: asp.net-core .net-core asp.net-core-2.0 hangfire coreclr