Hanfire没有使用元数据记录自定义异常

时间:2018-03-12 23:27:39

标签: asp.net-core .net-core asp.net-core-2.0 hangfire coreclr

我有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仅记录异常消息和堆栈跟踪。 我没有看到我的自定义属性被记录(即内容,RequestUri,HttpResponse)

在clssic .NET中,我们使用像这样SO post的SerializationInfo 如何在.NET Core中创建自定义异常,以便元数据也会被记录?

注意:
MyHttpRequestException被抛出时,我注意到异常的ToString()方法被调用     但是,我没有看到任何ToString()返回被Hangfire记录。     我不知道这是否是hangfire问题,或者我需要实现MyHttpRequestException是不同的方式。

1 个答案:

答案 0 :(得分:0)

您在仪表板中看到的堆栈跟踪已格式化。您可以看到herehere

因为这种自定义堆栈跟踪格式,您可以看到自定义属性。

相关问题