2

In C# (MVC 5 in particular), how can I get the name of a method where an exception occurs?

Here is my current code:

public async Task TestException()
{
    int result;
    int divider;
    divider = 0;
    try
    {
        result = 1 / divider;
    }
    catch (Exception ex)
    {
        string methodName = ex.TargetSite.Name;
        throw;
    }
}

I have also tried:

methodName = new System.Diagnostics.StackTrace(ex).GetFrame(0).GetMethod().Name;

The method name is being reported as "MoveNext" in both of the above code examples.

Thanks

pravprab
  • 2,301
  • 3
  • 26
  • 43
Simon
  • 7,991
  • 21
  • 83
  • 163
  • Both question says the same way. http://stackoverflow.com/questions/4598255/how-to-get-the-name-of-the-method-that-caused-the-exception and http://stackoverflow.com/questions/16666338/can-you-get-method-name-that-threw-exception – Soner Gönül Mar 02 '15 at 07:59
  • That's odd, is it the same for a non-`async Task` method? – weston Mar 02 '15 at 08:25
  • The exact same code, but in a non-async Task returns the method name correctly. – Simon Mar 02 '15 at 08:39
  • I think the only way you can do this is by using the `CallerMemberName` attribute to capture the method name, since the compiler rewrites the method because it is marked async. See my answer [here](http://stackoverflow.com/a/20159334/517852) for an example. – Mike Zboray Mar 02 '15 at 08:51
  • how about `string methodName = "TestException"`? – default Mar 02 '15 at 08:56

0 Answers0