mirror of
https://github.com/TeamOctolings/Octobot.git
synced 2025-01-31 00:19:00 +03:00
Octol1ttle
e457b4609e
This PR fixes an issue where the `LogResultStackTrace` method would log stack traces for results that encountered an error due to a cancelled operation/task. The `LoggerExtensions` class already skipped `TaskCanceledException`s, but didn't skip `OperationCanceledException`s (which is a parent of `TaskCanceledException`). The patch specifically does not affect *inner* results which are canceled. Skipping logging these could hide the true cause of an error which appears important
65 lines
1.9 KiB
C#
65 lines
1.9 KiB
C#
using System.Diagnostics;
|
|
using Microsoft.Extensions.Logging;
|
|
using Remora.Results;
|
|
|
|
namespace TeamOctolings.Octobot.Extensions;
|
|
|
|
public static class ResultExtensions
|
|
{
|
|
public static Result FromError(Result result)
|
|
{
|
|
LogResultStackTrace(result);
|
|
|
|
return result;
|
|
}
|
|
|
|
public static Result FromError<T>(Result<T> result)
|
|
{
|
|
var casted = (Result)result;
|
|
LogResultStackTrace(casted);
|
|
|
|
return casted;
|
|
}
|
|
|
|
private static void LogResultStackTrace(Result result)
|
|
{
|
|
if (result.IsSuccess || result.Error is ExceptionError { Exception: OperationCanceledException })
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (Utility.StaticLogger is null)
|
|
{
|
|
throw new InvalidOperationException();
|
|
}
|
|
|
|
Utility.StaticLogger.LogError("{ErrorType}: {ErrorMessage}{NewLine}{StackTrace}",
|
|
result.Error.GetType().FullName, result.Error.Message, Environment.NewLine, ConstructStackTrace());
|
|
|
|
var inner = result.Inner;
|
|
while (inner is { IsSuccess: false })
|
|
{
|
|
Utility.StaticLogger.LogError("Caused by: {ResultType}: {ResultMessage}",
|
|
inner.Error.GetType().FullName, inner.Error.Message);
|
|
|
|
inner = inner.Inner;
|
|
}
|
|
}
|
|
|
|
private static string ConstructStackTrace()
|
|
{
|
|
var stackArray = new StackTrace(3, true).ToString().Split(Environment.NewLine).ToList();
|
|
for (var i = stackArray.Count - 1; i >= 0; i--)
|
|
{
|
|
var frame = stackArray[i];
|
|
var trimmed = frame.TrimStart();
|
|
if (trimmed.StartsWith("at System.Threading", StringComparison.Ordinal)
|
|
|| trimmed.StartsWith("at System.Runtime.CompilerServices", StringComparison.Ordinal))
|
|
{
|
|
stackArray.RemoveAt(i);
|
|
}
|
|
}
|
|
|
|
return string.Join(Environment.NewLine, stackArray);
|
|
}
|
|
}
|