0

I am trying to handle all the exceptions thrown from a async method, but when i throw the exception after the execution of an async child method,then on re-throw exception from fody(OnException method) application breaks.

Like:

using MethodBoundaryAspect.Fody.Attributes;

public sealed class ExceptionHandlerAttribute : OnMethodBoundaryAspect
{

    public override void OnException(MethodExecutionArgs args)
    {
        //re-throw exception
        throw args.Exception;
    }
}

public class ClassName
{
    [ExceptionHandler]
    public async Task<T> MethodAsync()
    {
        //do some async work
        await OtherClass.DoSomeWorkAsync();
        throw new Exception("Exception after the execution of an Async method");
    }
}

public class ParentClass
{
    public async Task<T> MethodAsync()
    {
        try
        {
            ClassName className=new ClassName();
            await className.MethodAsync();
        }
        catch(Exception ex)
        {
        }
    }
}
Joe Mayo
  • 7,501
  • 7
  • 41
  • 60
  • 1
    How does the application break? – Paulo Morgado Sep 01 '20 at 19:39
  • @PauloMorgado execute the above code in a WEB application. – Mohsin Zubair Sep 01 '20 at 19:51
  • So, who is catching the exception, or who do you expect to catch it? Are you sure that `OnException` should re-throw? – Andrew Sep 01 '20 at 20:01
  • @Andrew i have just added some more detail in code kindly recheck it. – Mohsin Zubair Sep 01 '20 at 20:13
  • Just run it outside the debugger. Then it won't break. – Stephen Cleary Sep 01 '20 at 20:34
  • I'd say it's not catching it because it's in a separate thread. [Related question](https://stackoverflow.com/questions/5983779/catch-exception-that-is-thrown-in-different-thread). Still, are you supposed to throw an exception in `OnException`? I think that method is supposed to handle errors, not produce them. – Andrew Sep 01 '20 at 20:35
  • @Andrew I know the method is used to handle exceptions but in my application it is used to catch and re-throw exception in some cases like if the exception is not a custom exception then log and throw a custom exception. – Mohsin Zubair Sep 02 '20 at 18:11
  • @StephenCleary I have tried it "outside the debugger" but the application still breaks. – Mohsin Zubair Sep 02 '20 at 18:23
  • Maybe it's something to Fody-specific. Could this work inside `OnException`? `ExceptionDispatchInfo.Capture(args.Exception).Throw();` I found it in [this discussion](https://github.com/vescon/MethodBoundaryAspect.Fody/issues/5). – Andrew Sep 03 '20 at 01:17

0 Answers0