From f02c202b15d713b457a41824459f7c33413d3316 Mon Sep 17 00:00:00 2001 From: zhifenglee-aelf Date: Tue, 8 Oct 2024 13:34:48 +0800 Subject: [PATCH] feat(exception handler): improved readability --- AOPExceptionModule/ExceptionHandler.cs | 17 +++++++++++++++-- AOPExceptionModule/FooClass.cs | 9 +++------ 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/AOPExceptionModule/ExceptionHandler.cs b/AOPExceptionModule/ExceptionHandler.cs index 0772e0b..e73e40a 100644 --- a/AOPExceptionModule/ExceptionHandler.cs +++ b/AOPExceptionModule/ExceptionHandler.cs @@ -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 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) { @@ -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; } diff --git a/AOPExceptionModule/FooClass.cs b/AOPExceptionModule/FooClass.cs index d77370b..59f3677 100644 --- a/AOPExceptionModule/FooClass.cs +++ b/AOPExceptionModule/FooClass.cs @@ -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) @@ -52,7 +49,7 @@ public async Task 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!");