Skip to content

Commit

Permalink
feat(return): added returning of new or default
Browse files Browse the repository at this point in the history
  • Loading branch information
zhifenglee-aelf committed Oct 11, 2024
1 parent c6303c4 commit ec5d9fa
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 1 deletion.
37 changes: 36 additions & 1 deletion AElf.ExceptionHandler/ExceptionHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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 };
Expand Down Expand Up @@ -352,4 +378,13 @@ private static Func<object, object[], Task> CreateFinallyMethod(Type targetType,

return methodToCall;
}

private static object GetDefaultValue(Type type)
{
if(type.IsValueType)
{
return Activator.CreateInstance(type);
}
return null;
}
}
1 change: 1 addition & 0 deletions AElf.ExceptionHandler/ExceptionHandlerAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
8 changes: 8 additions & 0 deletions AElf.ExceptionHandler/ReturnDefault.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace AElf.ExceptionHandler;

public enum ReturnDefault
{
None,
Default,
New
}

0 comments on commit ec5d9fa

Please sign in to comment.