PowerShellEditorServices
PowerShellEditorServices copied to clipboard
Ensure errors in unawaited Tasks are caught with ContinueWith
Right now there are a bunch of tasks we fire off in PSES that are never awaited, meaning any errors thrown by those tasks are never handled or even logged. We need to add continuation handlers to those tasks to ensure we know about all failures occurring in PSES.
I looked into this today and couldn't find anywhere outside of testing that seemed to need this (which surprised me).
In case we want to revisit it later, ContinueWith is discouraged. The pattern I suggest instead is:
internal static Task HandleErrorsAsync(this Task task, ILogger logger, string taskDescription)
{
return task.IsCompletedSuccessfully
? task
: LogTaskErrors(task, logger, taskDescription);
}
private static async Task LogTaskErrors(Task task, ILogger logger, string taskDescription)
{
try
{
await task.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
logger.LogDebug($"Task canceled: '{taskDescription}'");
throw;
}
catch (Exception e)
{
logger.LogError(e, $"Exception thrown running task '{taskDescription}'");
throw;
}
}