2020-12-23 16:10:02 +08:00
|
|
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
|
|
|
|
// See the LICENCE file in the repository root for full licence text.
|
|
|
|
|
2020-12-31 18:29:02 +08:00
|
|
|
#nullable enable
|
|
|
|
|
|
|
|
using System;
|
2020-12-23 16:10:02 +08:00
|
|
|
using System.Threading.Tasks;
|
2020-12-31 18:29:02 +08:00
|
|
|
using osu.Framework.Extensions.ExceptionExtensions;
|
2020-12-23 16:10:02 +08:00
|
|
|
using osu.Framework.Logging;
|
|
|
|
|
|
|
|
namespace osu.Game.Extensions
|
|
|
|
{
|
|
|
|
public static class TaskExtensions
|
|
|
|
{
|
|
|
|
/// <summary>
|
|
|
|
/// Denote a task which is to be run without local error handling logic, where failure is not catastrophic.
|
|
|
|
/// Avoids unobserved exceptions from being fired.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="task">The task.</param>
|
2020-12-31 18:29:02 +08:00
|
|
|
/// <param name="logAsError">
|
|
|
|
/// Whether errors should be logged as errors visible to users, or as debug messages.
|
|
|
|
/// Logging as debug will essentially silence the errors on non-release builds.
|
|
|
|
/// </param>
|
|
|
|
public static void CatchUnobservedExceptions(this Task task, bool logAsError = false)
|
2020-12-23 16:10:02 +08:00
|
|
|
{
|
|
|
|
task.ContinueWith(t =>
|
|
|
|
{
|
2020-12-31 18:29:02 +08:00
|
|
|
Exception? exception = t.Exception?.AsSingular();
|
|
|
|
if (logAsError)
|
|
|
|
Logger.Error(exception, $"Error running task: {exception?.Message ?? "(unknown)"}", LoggingTarget.Runtime, true);
|
|
|
|
else
|
|
|
|
Logger.Log($"Error running task: {exception}", LoggingTarget.Runtime, LogLevel.Debug);
|
2020-12-23 16:10:02 +08:00
|
|
|
}, TaskContinuationOptions.NotOnRanToCompletion);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|