mirror of
https://github.com/ppy/osu.git
synced 2024-11-07 08:07:23 +08:00
2d279350ad
Silencing an exception from a task continuation requires accessing `task.Exception` in any way, which was not done previously if `logOnError` was false. To resolve without having to worry whether the compiler will optimise away a useless access or now, just always log, but switch the logging level. The unimportant errors will be logged as debug and therefore essentially silenced on release builds (but could still be potentially useful in debugging).
37 lines
1.4 KiB
C#
37 lines
1.4 KiB
C#
// 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.
|
|
|
|
#nullable enable
|
|
|
|
using System;
|
|
using System.Threading.Tasks;
|
|
using osu.Framework.Extensions.ExceptionExtensions;
|
|
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>
|
|
/// <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)
|
|
{
|
|
task.ContinueWith(t =>
|
|
{
|
|
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);
|
|
}, TaskContinuationOptions.NotOnRanToCompletion);
|
|
}
|
|
}
|
|
}
|