Skip to content

Commit

Permalink
feat(exception handler): improved readability
Browse files Browse the repository at this point in the history
  • Loading branch information
zhifenglee-aelf committed Oct 8, 2024
1 parent 9bfd008 commit f02c202
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
17 changes: 15 additions & 2 deletions AOPExceptionModule/ExceptionHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,21 @@ private class MethodInfo

public Type TargetType { get; set; }
public string MethodName { get; set; }
public Type Exception { get; set; }
private Type[] Exceptions { get; set; }

private static readonly ConcurrentDictionary<string, MethodInfo> MethodCache = new();

public ExceptionHandler(params Type [] exceptions)
{
// loop through to check if all types are exceptions
if (exceptions.Any(exception => !typeof(Exception).IsAssignableFrom(exception)))
{
throw new ArgumentException("All types must be exceptions");
}

Exceptions = exceptions;
//SemanticallyAdvisedMethodKinds = SemanticallyAdvisedMethodKinds.None;
}

public override void OnException(MethodExecutionArgs args)
{
Expand All @@ -38,7 +50,8 @@ public override void OnException(MethodExecutionArgs args)

private void HandleInnerException(Exception exception, MethodExecutionArgs args)
{
if(!Exception.IsInstanceOfType(args.Exception))
// If the exception is not of the specified type, return early
if (!Exceptions.Any(e => e.IsInstanceOfType(exception)))
{
return;
}
Expand Down
9 changes: 3 additions & 6 deletions AOPExceptionModule/FooClass.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,10 @@ public async Task Execute(int index)
//throw new Exception("Test exception");
}

[ExceptionHandler(Exception = typeof(Exception),
[ExceptionHandler(typeof(Exception),
TargetType = typeof(FooClass),
MethodName = nameof(HandleException))]
[ExceptionHandler(Exception = typeof(InvalidOperationException),
TargetType = typeof(FooClass),
MethodName = nameof(HandleException))]
[ExceptionHandler(Exception = typeof(ArgumentException),
[ExceptionHandler([typeof(ArgumentException), typeof(InvalidOperationException)],
TargetType = typeof(StaticClass),
MethodName = nameof(StaticClass.HandleException))]
private async Task BooExecute(int i)
Expand All @@ -52,7 +49,7 @@ public async Task<ExceptionHandlingStrategy> HandleException(Exception ex, int i
return ExceptionHandlingStrategy.Continue;
}

[ExceptionHandler(TargetType = typeof(FooClass), MethodName = nameof(HandleBooException))]
[ExceptionHandler(typeof(Exception), TargetType = typeof(FooClass), MethodName = nameof(HandleBooException))]
public async Task ExecuteBoo(int index, BooData data)
{
Console.WriteLine("Hello, World!");
Expand Down

0 comments on commit f02c202

Please sign in to comment.