diff --git a/AElf.ExceptionHandler/ExceptionHandler.cs b/AElf.ExceptionHandler/ExceptionHandler.cs index 2e23820..1b8ea92 100644 --- a/AElf.ExceptionHandler/ExceptionHandler.cs +++ b/AElf.ExceptionHandler/ExceptionHandler.cs @@ -36,7 +36,7 @@ public async Task InterceptAsync(MethodExecutionArgs args) catch (Exception e) { var result = OnException(e, args); - if (result != null && (result.Rethrow || !result.Handled)) + if (result == null || result.Rethrow || !result.Handled) { throw; } @@ -194,6 +194,32 @@ private Result HandleInnerException(Exception exception, MethodExecutionArgs arg }; } + if(attribute.ReturnDefault != ReturnDefault.None) + { + var returnType = args.MethodInfo.ReturnType; + Type? genericType = null; + + if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task<>)) + { + genericType = returnType.GetGenericArguments()[0]; + } + + if (genericType != null) + { + args.ReturnValue = attribute.ReturnDefault switch + { + ReturnDefault.Default => GetDefaultValue(genericType), + ReturnDefault.New => Activator.CreateInstance(genericType) + }; + + return new Result + { + Handled = true, + Rethrow = false + }; + } + } + var exceptionHandlerInfo = GetExceptionHandlerInfo(attribute.TargetType, attribute.MethodName); var parameters = new object[] { exception }; @@ -352,4 +378,13 @@ private static Func CreateFinallyMethod(Type targetType, return methodToCall; } + + private static object GetDefaultValue(Type type) + { + if(type.IsValueType) + { + return Activator.CreateInstance(type); + } + return null; + } } \ No newline at end of file diff --git a/AElf.ExceptionHandler/ExceptionHandlerAttribute.cs b/AElf.ExceptionHandler/ExceptionHandlerAttribute.cs index 104391f..5525ed0 100644 --- a/AElf.ExceptionHandler/ExceptionHandlerAttribute.cs +++ b/AElf.ExceptionHandler/ExceptionHandlerAttribute.cs @@ -13,6 +13,7 @@ public class ExceptionHandlerAttribute : Attribute public Type? FinallyTargetType { get; set; } = null; public string? FinallyMethodName { get; set; } = null; public string? Message { get; set; } = null; + public ReturnDefault ReturnDefault { get; set; } = ReturnDefault.None; public ExceptionHandlerAttribute(params Type [] exceptions) { diff --git a/AElf.ExceptionHandler/ReturnDefault.cs b/AElf.ExceptionHandler/ReturnDefault.cs new file mode 100644 index 0000000..f08ae09 --- /dev/null +++ b/AElf.ExceptionHandler/ReturnDefault.cs @@ -0,0 +1,8 @@ +namespace AElf.ExceptionHandler; + +public enum ReturnDefault +{ + None, + Default, + New +} \ No newline at end of file