This repository was archived by the owner on Jun 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathTaskExtensions.cs
More file actions
76 lines (69 loc) · 2.2 KB
/
Copy pathTaskExtensions.cs
File metadata and controls
76 lines (69 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;
using System.Threading.Tasks;
using GitHub.Logging;
using Serilog;
namespace GitHub.Extensions
{
public static class TaskExtensions
{
static readonly ILogger log = LogManager.ForContext(typeof(TaskExtensions));
public static async Task<T> Catch<T>(this Task<T> source, Func<Exception, T> handler = null)
{
Guard.ArgumentNotNull(source, nameof(source));
try
{
return await source;
}
catch (Exception ex)
{
if (handler != null)
return handler(ex);
return default(T);
}
}
public static async Task Catch(this Task source, Action<Exception> handler = null)
{
Guard.ArgumentNotNull(source, nameof(source));
try
{
await source;
}
catch (Exception ex)
{
if (handler != null)
handler(ex);
}
}
/// <summary>
/// Allow task to run and log any exceptions.
/// </summary>
/// <param name="task">The <see cref="Task"/> to log exceptions from.</param>
/// <param name="errorMessage">An error message to log if the task throws.</param>
public static void Forget(this Task task, string errorMessage = "")
{
task.ContinueWith(t =>
{
if (t.IsFaulted)
{
log.Error(t.Exception, errorMessage);
}
});
}
/// <summary>
/// Allow task to run and log any exceptions.
/// </summary>
/// <param name="task">The task to log exceptions from.</param>
/// <param name="log">The logger to use.</param>
/// <param name="errorMessage">The error message to log if the task throws.</param>
public static void Forget(this Task task, ILogger log, string errorMessage = "")
{
task.ContinueWith(t =>
{
if (t.IsFaulted)
{
log.Error(t.Exception, errorMessage);
}
});
}
}
}