How to get the name of the method that caused the exception

后端 未结 3 1063
梦毁少年i
梦毁少年i 2020-12-06 04:47

My code looks as below.

try
{
    _productRepo.GetAllProductCategories();
}
catch (Exception ex)
{
    //Do Something
}

I need a way to sho

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-06 05:44

    There's a TargetSite property on System.Exception that should come in handy.

    Gets the method that throws the current exception.

    In your case, you probably want something like:

    catch (Exception ex)
    {
       MethodBase site = ex.TargetSite;
       string methodName = site == null ? null : site.Name;
       ...           
    }
    

    It's worth pointing out some of the issues listed:

    If the method that throws this exception is not available and the stack trace is not a null reference (Nothing in Visual Basic), TargetSite obtains the method from the stack trace. If the stack trace is a null reference, TargetSite also returns a null reference.

    Note: The TargetSite property may not accurately report the name of the method in which an exception was thrown if the exception handler handles an exception across application domain boundaries.

    You could use the StackTrace property as @leppie suggests too, but do note that this is a string representation of the frames on the stack; so you'll have to manipulate if you only want the name of the method that threw the execption.

提交回复
热议问题