Fody异步方法装饰器处理异常

6

我正在尝试使用Fody来包装从方法抛出的所有异常,使其具有公共异常格式。

因此,我已添加了所需的接口声明和类实现,看起来像这样:

using System;
using System.Diagnostics;
using System.Reflection;
using System.Threading.Tasks;

[module: MethodDecorator]

public interface IMethodDecorator
{
  void Init(object instance, MethodBase method, object[] args);
  void OnEntry();
  void OnExit();
  void OnException(Exception exception);
  void OnTaskContinuation(Task t);
}


[AttributeUsage(
    AttributeTargets.Module |
    AttributeTargets.Method |
    AttributeTargets.Assembly |
    AttributeTargets.Constructor, AllowMultiple = true)]
public class MethodDecorator : Attribute, IMethodDecorator
{
  public virtual void Init(object instance, MethodBase method, object[] args) { }

  public void OnEntry()
  {
    Debug.WriteLine("base on entry");
  }

  public virtual void OnException(Exception exception)
  {
    Debug.WriteLine("base on exception");
  }

  public void OnExit()
  {
    Debug.WriteLine("base on exit");
  }

  public void OnTaskContinuation(Task t)
  {
    Debug.WriteLine("base on continue");
  }
}

而域实现看起来像这样

using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.ExceptionServices;

namespace CC.Spikes.AOP.Fody
{
  public class FodyError : MethodDecorator
  {
    public string TranslationKey { get; set; }
    public Type ExceptionType { get; set; }

    public override void Init(object instance, MethodBase method, object[] args)
    {
      SetProperties(method);
    }

    private void SetProperties(MethodBase method)
    {
      var attribute = method.CustomAttributes.First(n => n.AttributeType.Name == nameof(FodyError));
      var translation = attribute
        .NamedArguments
        .First(n => n.MemberName == nameof(TranslationKey))
        .TypedValue
        .Value
          as string;

      var exceptionType = attribute
        .NamedArguments
        .First(n => n.MemberName == nameof(ExceptionType))
        .TypedValue
        .Value
          as Type;


      TranslationKey = translation;
      ExceptionType = exceptionType;
    }

    public override void OnException(Exception exception)
    {
      Debug.WriteLine("entering fody error exception");
      if (exception.GetType() != ExceptionType)
      {
        Debug.WriteLine("rethrowing fody error exception");
        //rethrow without losing stacktrace
        ExceptionDispatchInfo.Capture(exception).Throw();
      }

      Debug.WriteLine("creating new fody error exception");
      throw new FodyDangerException(TranslationKey, exception);

    }
  }

  public class FodyDangerException : Exception
  {
    public string CallState { get; set; }
    public FodyDangerException(string message, Exception error) : base(message, error)
    {

    }
  }
}

这对于同步代码工作得很好。但是对于异步代码,异常处理程序被跳过,即使所有其他IMethodDecorator都已执行(例如 OnExit 和 OnTaskContinuation )。

例如,查看以下测试类:

public class FodyTestStub
{ 

  [FodyError(ExceptionType = typeof(NullReferenceException), TranslationKey = "EN_WHATEVER")]
  public async Task ShouldGetErrorAsync()
  {
    await Task.Delay(200);
    throw new NullReferenceException();
  }

  public async Task ShouldGetErrorAsync2()
  {
    await Task.Delay(200);
    throw new NullReferenceException();
  }
}

我看到ShouldGetErrorAsync生成了以下IL代码:

// CC.Spikes.AOP.Fody.FodyTestStub
[FodyError(ExceptionType = typeof(NullReferenceException), TranslationKey = "EN_WHATEVER"), DebuggerStepThrough, AsyncStateMachine(typeof(FodyTestStub.<ShouldGetErrorAsync>d__3))]
public Task ShouldGetErrorAsync()
{
    MethodBase methodFromHandle = MethodBase.GetMethodFromHandle(methodof(FodyTestStub.ShouldGetErrorAsync()).MethodHandle, typeof(FodyTestStub).TypeHandle);
    FodyError fodyError = (FodyError)Activator.CreateInstance(typeof(FodyError));
    object[] args = new object[0];
    fodyError.Init(this, methodFromHandle, args);
    fodyError.OnEntry();
    Task task;
    try
    {
        FodyTestStub.<ShouldGetErrorAsync>d__3 <ShouldGetErrorAsync>d__ = new FodyTestStub.<ShouldGetErrorAsync>d__3();
        <ShouldGetErrorAsync>d__.<>4__this = this;
        <ShouldGetErrorAsync>d__.<>t__builder = AsyncTaskMethodBuilder.Create();
        <ShouldGetErrorAsync>d__.<>1__state = -1;
        AsyncTaskMethodBuilder <>t__builder = <ShouldGetErrorAsync>d__.<>t__builder;
        <>t__builder.Start<FodyTestStub.<ShouldGetErrorAsync>d__3>(ref <ShouldGetErrorAsync>d__);
        task = <ShouldGetErrorAsync>d__.<>t__builder.Task;
        fodyError.OnExit();
    }
    catch (Exception exception)
    {
        fodyError.OnException(exception);
        throw;
    }
    return task;
}

ShouldGetErrorAsync2 生成:

    // CC.Spikes.AOP.Fody.FodyTestStub
[DebuggerStepThrough, AsyncStateMachine(typeof(FodyTestStub.<ShouldGetErrorAsync2>d__4))]
public Task ShouldGetErrorAsync2()
{
    FodyTestStub.<ShouldGetErrorAsync2>d__4 <ShouldGetErrorAsync2>d__ = new FodyTestStub.<ShouldGetErrorAsync2>d__4();
    <ShouldGetErrorAsync2>d__.<>4__this = this;
    <ShouldGetErrorAsync2>d__.<>t__builder = AsyncTaskMethodBuilder.Create();
    <ShouldGetErrorAsync2>d__.<>1__state = -1;
    AsyncTaskMethodBuilder <>t__builder = <ShouldGetErrorAsync2>d__.<>t__builder;
    <>t__builder.Start<FodyTestStub.<ShouldGetErrorAsync2>d__4>(ref <ShouldGetErrorAsync2>d__);
    return <ShouldGetErrorAsync2>d__.<>t__builder.Task;
}

如果我调用ShouldGetErrorAsync,Fody会拦截该调用,并在方法体中包装一个try catch。但是,如果该方法是异步的,即使fodyError.OnTaskContinuation(task)fodyError.OnExit()仍然被调用,它也永远不会触发catch语句。
另一方面,ShouldGetErrorAsync将很好地处理错误,即使在IL中没有错误处理块。
我的问题是,Fody应该如何生成IL以正确注入错误块并使异步错误被拦截? 这里有一个带有测试的存储库,可以重现此问题
2个回答

2
你只是将try-catch放在“kick-off”方法的内容周围,这只能保护你到第一次需要重新调度的时候(当异步方法需要重新调度时,“kick-off”方法将结束,并且在异步方法恢复时不会在堆栈上)。
相反,你应该查看实现IAsyncStateMachine.MoveNext()状态机的方法。特别是,在异步方法生成器(AsyncVoidMethodBuilderAsyncTaskMethodBuilderAsyncTaskMethodBuilder<TResult>)上查找对SetException(Exception)的调用,并在传递异常之前进行包装。

2
这在技术上是正确的,但实现起来很困难。最后我切换了库到 https://github.com/vescon/MethodBoundaryAspect.Fody。它处理异步问题,并且我发现该项目易于使用和修改。 - swestner

1
await让异步方法看起来很简单,是吗? :) 但你发现了这个抽象中的一个漏洞 - 方法通常在找到第一个await后立即返回,你的异常助手无法拦截任何后续的异常。
你需要做的是实现OnException并处理方法的返回值。当方法返回且任务未完成时,你需要在任务上启动一个错误继续操作,该操作需要以你想要处理异常的方式处理异常。 Fody的开发人员已经考虑到了这一点 - 这就是OnTaskContinuation的作用。你需要检查Task.Exception是否有潜藏在任务中的异常,并根据需要进行处理。
我认为只有在记录日志或其他类似情况下才能重新抛出异常 - 它不允许你用其他东西替换异常。你应该测试一下:)

很遗憾,你是正确的,错误只能被报告而无法重新处理。 - swestner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接