简体   繁体   中英

Using reflection to capture error details

I have a quick question that hopefully someone has worked through before. In the system that I am currently working on, we have rolled our own custom provider for handling web exceptions. One of the things that I like about this provider is that it allows us to add in parameter values of the method that throws the exception. The code looks something like this.

Public Sub Dosomething(ByVal Parameter1 As String, ByVal Parameter2 As String)
    Try
        'Do some process that causes and error.
    Catch ex As Exception
        Dim ErrorDetails = New List(Of String)

        ErrorDetails.Add("Parameter Values:")
        ErrorDetails.Add(String.Format("Parameter 1: {0}", Parameter1))
        ErrorDetails.Add(String.Format("Parameter 2: {0}", Parameter2))

        RaiseNewCustomException(ex, ErrorDetails)
    End Try
End Sub

In the case of this method, the capture of the parameters and their values is very manual and prone to error as more and more people touch the code base and forget to update the thrown error. Is there a way to approach this problem in a more automated / less error prone way?

I have played around with reflection, but I don't think you can ascertain the parameter values via reflection. I would like something like:

Public Sub Dosomething(ByVal Parameter1 As String, ByVal Parameter2 As String)
    Try
        'Do some process that causes and error.
    Catch ex As Exception
        RaiseNewCustomExceptionAndAutomaticallyGenerateParameterErrorString(ex, System.Reflection.MethodInfo.GetCurrentMethod())
    End Try
End Sub

It is not possible to use Reflection to retrieve method argument values. Only a debugger can have a shot at it, but even a debugger is powerless when the code is optimized. Argument passing is heavily optimized by the JIT compiler. Suppressing this optimization isn't worth the considerable cost, nor can an app debug itself.

As long as you want to keep this style of exception reporting, you'll have to explicitly pass the argument values to some kind of formatter. A helper function that takes a Params array and returns an exception object that you can throw jumps to mind.

Reflection will not give you the parameter values. This is discussed in Stack Overflow questions Using reflection to get method name and parameters and Obtain parameter values from a stack frame in .NET? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM