Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 131 additions & 0 deletions src/LuYao.Common/Guard.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
using System;
using System.Threading.Tasks;

namespace LuYao;

/// <summary>
/// Provides guarded execution helpers to reduce try/catch boilerplate
/// while keeping behavior observable and configurable.
/// </summary>
public static class Guard
{
/// <summary>
/// Executes an action with guarded exception handling.
/// </summary>
/// <param name="action">The action to execute.</param>
/// <param name="onError">An optional callback invoked when a handled exception is caught.</param>
/// <param name="when">An optional predicate to determine whether an exception should be handled.</param>
/// <param name="rethrow">If <see langword="true"/>, rethrows handled exceptions after invoking <paramref name="onError"/>.</param>
/// <returns><see langword="true"/> when execution succeeds; otherwise <see langword="false"/> for handled exceptions.</returns>
public static bool TryRun(Action action, Action<Exception>? onError = null, Func<Exception, bool>? when = null, bool rethrow = false)
{
if (action == null) throw new ArgumentNullException(nameof(action));

try
{
action();
return true;
}
catch (Exception ex) when (CanHandle(ex, when))
{
onError?.Invoke(ex);
if (rethrow) throw;
return false;
}
}

/// <summary>
/// Executes an asynchronous action with guarded exception handling.
/// </summary>
/// <param name="action">The asynchronous action to execute.</param>
/// <param name="onError">An optional callback invoked when a handled exception is caught.</param>
/// <param name="when">An optional predicate to determine whether an exception should be handled.</param>
/// <param name="rethrow">If <see langword="true"/>, rethrows handled exceptions after invoking <paramref name="onError"/>.</param>
/// <returns>A task that returns <see langword="true"/> when execution succeeds; otherwise <see langword="false"/> for handled exceptions.</returns>
public static async Task<bool> TryRunAsync(Func<Task> action, Action<Exception>? onError = null, Func<Exception, bool>? when = null, bool rethrow = false)
{
try
{
Comment on lines +45 to +48
await action();
return true;
}
catch (Exception ex) when (CanHandle(ex, when))
{
onError?.Invoke(ex);
if (rethrow) throw;
return false;
}
}

/// <summary>
/// Executes a function and returns its result, or a fallback value when a handled exception occurs.
/// </summary>
/// <typeparam name="T">The result type.</typeparam>
/// <param name="func">The function to execute.</param>
/// <param name="fallback">The fallback value returned when a handled exception occurs.</param>
/// <param name="onError">An optional callback invoked when a handled exception is caught.</param>
/// <param name="when">An optional predicate to determine whether an exception should be handled.</param>
/// <param name="rethrow">If <see langword="true"/>, rethrows handled exceptions after invoking <paramref name="onError"/>.</param>
/// <returns>The function result when successful; otherwise <paramref name="fallback"/> for handled exceptions.</returns>
public static T TryGet<T>(Func<T> func, T fallback = default!, Action<Exception>? onError = null, Func<Exception, bool>? when = null, bool rethrow = false)
{
if (func == null) throw new ArgumentNullException(nameof(func));

try
{
return func();
}
catch (Exception ex) when (CanHandle(ex, when))
{
onError?.Invoke(ex);
if (rethrow) throw;
return fallback;
}
}

/// <summary>
/// Executes an asynchronous function and returns its result,
/// or a fallback value when a handled exception occurs.
/// </summary>
/// <typeparam name="T">The result type.</typeparam>
/// <param name="func">The asynchronous function to execute.</param>
/// <param name="fallback">The fallback value returned when a handled exception occurs.</param>
/// <param name="onError">An optional callback invoked when a handled exception is caught.</param>
/// <param name="when">An optional predicate to determine whether an exception should be handled.</param>
/// <param name="rethrow">If <see langword="true"/>, rethrows handled exceptions after invoking <paramref name="onError"/>.</param>
/// <returns>A task that returns the function result when successful; otherwise <paramref name="fallback"/> for handled exceptions.</returns>
public static async Task<T> TryGetAsync<T>(Func<Task<T>> func, T fallback = default!, Action<Exception>? onError = null, Func<Exception, bool>? when = null, bool rethrow = false)
{
if (func == null) throw new ArgumentNullException(nameof(func));

try
{
return await func();
}
catch (Exception ex) when (CanHandle(ex, when))
{
onError?.Invoke(ex);
if (rethrow) throw;
return fallback;
}
}

private static bool CanHandle(Exception ex, Func<Exception, bool>? when)
{
if (IsCritical(ex)) return false;
if (when == null) return true;
return when(ex);
}
Comment on lines +113 to +118

private static bool IsCritical(Exception ex)
{
return ex is OperationCanceledException
|| ex is OutOfMemoryException
|| ex is StackOverflowException
|| ex is AccessViolationException
|| ex is AppDomainUnloadedException
|| ex is BadImageFormatException
|| ex is CannotUnloadAppDomainException
|| ex is InvalidProgramException;
}
}
95 changes: 95 additions & 0 deletions tests/LuYao.Common.UnitTests/GuardTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace LuYao;

[TestClass]
public class GuardTests
{
[TestMethod]
public void TryRun_WhenActionSucceeds_ReturnsTrue()
{
bool result = Guard.TryRun(() => { });

Assert.IsTrue(result);
}

[TestMethod]
public void TryRun_WhenActionThrows_ReturnsFalseAndInvokesOnError()
{
Exception? captured = null;

bool result = Guard.TryRun(() => throw new InvalidOperationException("boom"), ex => captured = ex);

Assert.IsFalse(result);
Assert.IsNotNull(captured);
Assert.IsInstanceOfType<InvalidOperationException>(captured);
}

[TestMethod]
public void TryRun_WhenRethrowIsTrue_RethrowsHandledException()
{
Assert.Throws<InvalidOperationException>(() =>
Guard.TryRun(() => throw new InvalidOperationException("boom"), rethrow: true));
}

[TestMethod]
public void TryRun_WhenFilterReturnsFalse_DoesNotHandleException()
{
Assert.Throws<InvalidOperationException>(() =>
Guard.TryRun(() => throw new InvalidOperationException("boom"), when: _ => false));
}

[TestMethod]
public void TryRun_WhenOperationCanceledExceptionThrown_DoesNotHandleException()
{
Assert.Throws<OperationCanceledException>(() =>
Guard.TryRun(() => throw new OperationCanceledException()));
}

[TestMethod]
public void TryGet_WhenFuncThrows_ReturnsFallback()
{
int value = Guard.TryGet(() => throw new InvalidOperationException("boom"), fallback: 42);

Assert.AreEqual(42, value);
}

Comment on lines +49 to +56
[TestMethod]
public async Task TryRunAsync_WhenActionThrows_ReturnsFalseAndInvokesOnError()
{
Exception? captured = null;

bool result = await Guard.TryRunAsync(
async () =>
{
await Task.Yield();
throw new InvalidOperationException("boom");
},
ex => captured = ex);

Assert.IsFalse(result);
Assert.IsNotNull(captured);
Assert.IsInstanceOfType<InvalidOperationException>(captured);
}

[TestMethod]
public async Task TryRunAsync_WhenOperationCanceledExceptionThrown_DoesNotHandleException()
{
await Assert.ThrowsAsync<OperationCanceledException>(async () =>
await Guard.TryRunAsync(async () =>
{
await Task.Yield();
throw new OperationCanceledException();
}));
}

[TestMethod]
public async Task TryGetAsync_WhenFuncThrows_ReturnsFallback()
{
int value = await Guard.TryGetAsync(
() => Task.FromException<int>(new InvalidOperationException("boom")),
fallback: 64);

Assert.AreEqual(64, value);
}
}
Loading