|
1 | 1 | using System; |
2 | 2 | using System.Threading.Tasks; |
| 3 | +using GitHub.Logging; |
3 | 4 | using Serilog; |
4 | 5 |
|
5 | 6 | namespace GitHub.Extensions |
6 | 7 | { |
7 | 8 | public static class TaskExtensions |
8 | 9 | { |
| 10 | + static readonly ILogger log = LogManager.ForContext(typeof(TaskExtensions)); |
| 11 | + |
9 | 12 | public static async Task<T> Catch<T>(this Task<T> source, Func<Exception, T> handler = null) |
10 | 13 | { |
11 | 14 | Guard.ArgumentNotNull(source, nameof(source)); |
@@ -37,23 +40,35 @@ public static async Task Catch(this Task source, Action<Exception> handler = nul |
37 | 40 | } |
38 | 41 | } |
39 | 42 |
|
40 | | - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "task")] |
41 | | - public static void Forget(this Task task) |
| 43 | + /// <summary> |
| 44 | + /// Allow task to run and log any exceptions. |
| 45 | + /// </summary> |
| 46 | + /// <param name="task">The <see cref="Task"/> to log exceptions from.</param> |
| 47 | + /// <param name="errorMessage">An error message to log if the task throws.</param> |
| 48 | + public static void Forget(this Task task, string errorMessage = "") |
42 | 49 | { |
| 50 | + task.ContinueWith(t => |
| 51 | + { |
| 52 | + if (t.IsFaulted) |
| 53 | + { |
| 54 | + log.Error(t.Exception, errorMessage); |
| 55 | + } |
| 56 | + }); |
43 | 57 | } |
44 | 58 |
|
45 | 59 | /// <summary> |
46 | | - /// Log any exceptions when a task throws. |
| 60 | + /// Allow task to run and log any exceptions. |
47 | 61 | /// </summary> |
48 | | - /// <param name="task">The <see cref="Task"/> to log exceptions from.</param> |
49 | | - /// <param name="log">The <see cref="ILogger"/> to use.</param> |
50 | | - public static void Forget(this Task task, ILogger log) |
| 62 | + /// <param name="task">The task to log exceptions from.</param> |
| 63 | + /// <param name="log">The logger to use.</param> |
| 64 | + /// <param name="errorMessage">The error message to log if the task throws.</param> |
| 65 | + public static void Forget(this Task task, ILogger log, string errorMessage = "") |
51 | 66 | { |
52 | 67 | task.ContinueWith(t => |
53 | 68 | { |
54 | 69 | if (t.IsFaulted) |
55 | 70 | { |
56 | | - log.Error(t.Exception, nameof(Forget)); |
| 71 | + log.Error(t.Exception, errorMessage); |
57 | 72 | } |
58 | 73 | }); |
59 | 74 | } |
|
0 commit comments