In a .net Exception how to get a stacktrace with argument values

前端 未结 11 1430
南方客
南方客 2020-12-01 01:58

I am trying to add an unhandled exception handler in .net (c#) that should be as helpfull for the \'user\' as possible. The end users are mostly programers so they just need

11条回答
  •  被撕碎了的回忆
    2020-12-01 02:50

    Likewise, I've not found anything to derive the parameters automatically at runtime. Instead, I've used a Visual Studio add-in to generate code that explicitly packages up the parameters, like this:

    public class ExceptionHandler
    {
        public static bool HandleException(Exception ex, IList parameters)
        {
            /*
             * Log the exception
             * 
             * Return true to rethrow the original exception,
             * else false
             */
        }
    }
    
    public class Param
    {
        public string Name { get; set; }
        public object Value { get; set; }
    }
    
    public class MyClass
    {
        public void RenderSomeText(int lineNumber, string text, RenderingContext context)
        {
            try
            {
                /*
                 * Do some work
                 */
                throw new ApplicationException("Something bad happened");
            }
            catch (Exception ex)
            {
                if (ExceptionHandler.HandleException(
                        ex, 
                        new List
                        {
                            new Param { Name = "lineNumber", Value=lineNumber },
                            new Param { Name = "text", Value=text },
                            new Param { Name = "context", Value=context}
                        }))
                {
                    throw;
                }
            }
        }
    }
    

    EDIT: or alternatively, by making the parameter to HandleException a params array:

    public static bool HandleException(Exception ex, params Param[] parameters)
    {
       ...
    }
    
    ...
    if (ExceptionHandler.HandleException(
                        ex, 
                        new Param { Name = "lineNumber", Value=lineNumber },
                        new Param { Name = "text", Value=text },
                        new Param { Name = "context", Value=context}
                        ))
    {
        throw;
    }
    ...
    

    It's a bit of a pain generating the extra code to explicitly pass the parameters to the exception handler, but with the use of an add-in you can at least automate it.

    A custom attribute can be used to annotate any parameters that you don't want the add-in to pass to the exception handler:

    public UserToken RegisterUser( string userId, [NoLog] string password )
    {
    }
    

    2ND EDIT:

    Mind you, I'd completely forgotten about AVICode:

    http://www.avicode.com/

    They use call interception techniques to provide exactly this kind of information, so it must be possible.

提交回复
热议问题