Skip to content

Commit 6a52540

Browse files
authored
Merge pull request #90 from prom-client-net/feat/on-push-error
add error handling method
2 parents 4856754 + ebb940f commit 6a52540

File tree

3 files changed

+32
-2
lines changed

3 files changed

+32
-2
lines changed

src/MetricPusherHostedService.cs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,14 @@ async Task DoPushAsync()
3636
{
3737
await pusher.PushAsync();
3838
}
39-
catch (Exception)
39+
catch (Exception ex)
4040
{
41-
// TODO: report error to DiagnosticSource?
41+
OnPushError(pusher, ex);
4242
}
4343
}
4444
}
45+
46+
protected virtual void OnPushError(IMetricPusher metricPusher, Exception exception)
47+
{
48+
}
4549
}

tests/MetricPusherHostedServiceTests.cs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,21 @@ public async Task WithGivenInterval_PushMetricPeriodically(int seconds)
3737
await metricPusherMock.Received(3).PushAsync();
3838
}
3939

40+
[Fact]
41+
public async Task OnPushError_HandlesException()
42+
{
43+
var pusher = Substitute.For<IMetricPusher>();
44+
pusher.PushAsync().Returns(Task.FromException(new Exception("Simulated Push Exception")));
45+
var ct = Arg.Any<CancellationToken>();
46+
47+
var hostedService = new TestableMetricPusherHostedService(pusher);
48+
await hostedService.StartAsync(ct);
49+
await Task.Delay(1000, ct);
50+
await hostedService.StopAsync(ct);
51+
52+
Assert.True(hostedService.ErrorHandled);
53+
}
54+
4055
private static TimeSpan GetDelay(int seconds)
4156
{
4257
var milliseconds = seconds * 1000 + 100;
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
namespace Prometheus.Client.MetricPusher.HostedService.Tests;
2+
3+
public class TestableMetricPusherHostedService(IMetricPusher pusher) : MetricPusherHostedService(pusher)
4+
{
5+
public bool ErrorHandled { get; private set; }
6+
7+
protected override void OnPushError(IMetricPusher metricPusher, Exception exception)
8+
{
9+
ErrorHandled = true;
10+
}
11+
}

0 commit comments

Comments
 (0)