PowerShellEditorServices icon indicating copy to clipboard operation
PowerShellEditorServices copied to clipboard

Ensure errors in unawaited Tasks are caught with ContinueWith

Open rjmholt opened this issue 4 years ago • 1 comments

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.

rjmholt avatar Mar 15 '21 22:03 rjmholt

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;
    }
}

rjmholt avatar Apr 29 '21 16:04 rjmholt