I'm trying to make an exception interceptor in my Xamarin application. Right now I'm juste trying to intercept service's methods: the call from view model to buisiness logic (all in one project, full .net standard 2).
I fall upon this answer (using autofac) and found it simple and clever. It works fine, I add a try-catch to get my exception, so far so good.
But then I tried to return my exception in a DTO object type. All our services return a Task of a DTO class derived from a DTOBase
abstract class. Theses classes just hold a reference to the value(s) and a IEnumerable
of exception named Errors
.
So basically, I try to catch the exception, put it in the list of Errors and return my object. I finished with this code :
public class ExceptionInterceptorBehaviour : IInterceptor
{
public void Intercept(IInvocation invocation)
{
invocation.Proceed();
var method = invocation.MethodInvocationTarget;
var isAsync = method.GetCustomAttribute(typeof(AsyncStateMachineAttribute)) != null;
if (isAsync && typeof(Task).IsAssignableFrom(method.ReturnType))
{
invocation.ReturnValue = InterceptAsync((dynamic)invocation.ReturnValue);
}
}
private static async Task InterceptAsync(Task task)
{
await task.ConfigureAwait(false);
}
private static async Task<T> InterceptAsync<T>(Task<T> task)
{
try
{
T result = await task.ConfigureAwait(false);
return result;
}
catch (Exception e)
{
if (typeof(DTOBase).IsAssignableFrom(typeof(T)))
{
var ret = Activator.CreateInstance(typeof(T));
(ret as DTOBase).Errors.Add(e);
return (T)ret;
}
throw e;
}
}
}
My probleme is that the application crashes at the return of Task<T> InterceptAsync<T>(Task<T> task)
. No exception is raised, no pause mode in the debugger just a plain crash.
I suspect a segmentation error, but my cast does work (I tested it) and I do return a Task<T>
and assign it to a Task<T>
object.
Am I missing something? I don't get why it crashes like that.