创建处理任务的异常转换动态代理
本文关键字:转换 动态 代理 异常 处理 任务 创建 | 更新日期: 2023-09-27 17:56:13
>问题
我不知何故在绕圈子...我尝试使用城堡动态代理创建具有目标的接口代理。代理应
- 如果没有抛出异常(即不执行任何操作),则返回调用的返回值。
- 如果调用引发
InvalidOperationException
,则抛出新的InterceptedException
。 - 如果调用抛出另一个异常
e
,则抛出e
。
器应捕获并转换特定的异常类型,而不是在所有其他情况下进行拦截。
我得到了这个同步方法的工作。但是,对于返回任务的异步方法,我需要相同的行为。
我尝试了什么
我尝试向返回的任务添加延续并检查IsFaulted
和Exception
(类似于此答案。这适用于返回 Task
的方法,但不适用于返回Task<T>
的方法,因为我的延续是 Task
类型(我不知道拦截器中的T
是什么)。
涵盖上述三种异步方法情况的测试 (XUnit.net)
public class ConvertNotFoundInterceptorTest
{
[Fact]
public void Non_throwing_func_returns_a_result()
{
Assert.Equal(43, RunTest(i => i + 1));
}
[Fact]
public void InvalidOperationExceptions_are_converted_to_IndexOutOfRangeExceptions()
{
var exception = Assert.Throws<AggregateException>(() => RunTest(i => { throw new InvalidOperationException("ugh"); }));
Assert.True(exception.InnerException is IndexOutOfRangeException);
}
[Fact]
public void Other_exceptions_are_preserved()
{
var exception = Assert.Throws<AggregateException>(() => RunTest(i => { throw new ArgumentException("ugh"); }));
Assert.True(exception.InnerException is ArgumentException);
}
private static int RunTest(Func<int, int> func)
{
var generator = new ProxyGenerator();
var proxiedSubject = generator.CreateInterfaceProxyWithTarget<ISubject>(new Subject(func), new ConvertNotFoundInterceptor());
return proxiedSubject.DoAsync(42).Result;
}
public interface ISubject
{
Task<int> DoAsync(int input);
}
public class Subject : ISubject
{
private readonly Func<int, int> _func;
public Subject(Func<int, int> func)
{
_func = func;
}
public async Task<int> DoAsync(int input)
{
return await Task.Run(() => _func(input));
}
}
}
拦截 器
public class ConvertNotFoundInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
invocation.Proceed();
var task = invocation.ReturnValue as Task;
if (task != null)
{
var continuation = task.ContinueWith(
t =>
{
if (t.Exception != null && t.Exception.InnerException is InvalidOperationException)
{
throw new IndexOutOfRangeException();
}
}, TaskContinuationOptions.OnlyOnFaulted);
// The following line fails (InvalidCastException: Unable to cast object
// of type 'System.Threading.Tasks.ContinuationTaskFromTask'
// to type 'System.Threading.Tasks.Task`1[System.Int32]'.)
invocation.ReturnValue = continuation;
}
}
}
请注意,此处所示的实现不考虑同步情况。我故意省略了这一部分。
问题
将上述拦截逻辑添加到异步方法的正确方法是什么?
好的,这不适用于Task<dynamic>
,因为城堡动态代理要求ReturnValue
是完全匹配的类型。但是,您可以通过使用 dynamic
进行调度来相当优雅地完成此操作:
public class ConvertNotFoundInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
invocation.Proceed();
var task = invocation.ReturnValue as Task;
if (task != null)
invocation.ReturnValue = ConvertNotFoundAsync((dynamic)task);
}
private static async Task ConvertNotFoundAsync(Task source)
{
try
{
await source.ConfigureAwait(false);
}
catch (InvalidOperationException)
{
throw new IndexOutOfRangeException();
}
}
private static async Task<T> ConvertNotFoundAsync<T>(Task<T> source)
{
try
{
return await source.ConfigureAwait(false);
}
catch (InvalidOperationException)
{
throw new IndexOutOfRangeException();
}
}
}
我非常喜欢async
/await
语法,因为它们可以正确处理使用 ContinueWith
棘手的边缘情况。