Get values of parameters in stack trace

2019-02-16 18:08发布

I am having trouble reproducing a few errors we are seeing in our error log.

It could be made a lot easier if I knew which record ID a specific method was using when it threw an exception.

All of our unhandled exceptions get handled by our global exception handler, which puts all the details of the exception, as well as all the details of the HTTP request, into a log table.

Is there a way to capture the values of all the parameters for the method that threw an exception? Or even better, all the values up the stack trace?

3条回答
Emotional °昔
2楼-- · 2019-02-16 18:18

Unfortunately, this is not possible: at the time when you catch the exception in the handler, all the stack frames with the method parameters are gone. Once the control leaves your function, you can no longer access its parameter values.

Since you know the specific function where the crash happens, you could set up an exception handler there to collect all the parameters of interest, and re-throw a wrapped exception. Once the diagnostics is complete, you could revert the code back to normal:

void SuspiciousFunction(string name, long count) {
    try {
        // The code of your function goes here
    } catch (Exception e) {
        var args = new Dictionary<string,object> {
            { "name" , name  }
        ,   { "count", count }
        };
        throw new MySpecialException(e, args);
    }
}
查看更多
成全新的幸福
3楼-- · 2019-02-16 18:21

I would capture the exception in the method it's thrown, gather your parameters and any other needed info, then rethrow the error with a new ApplicationException or other custom Exception that contains your additional info.

查看更多
Ridiculous、
4楼-- · 2019-02-16 18:32

From the documentation Environment.StackTrace i would say it is possible. They say

The stack trace information for each method call is formatted as follows:

"at FullClassName. MethodName (MethodParams) in FileName :line LineNumber "

查看更多
登录 后发表回答