简体   繁体   中英

Get Specific information from thrown exception

Lets consider that we have an Exception ex thrown in the code. Now in the catch body, I want to have access to six pieces of information:

  1. Solution Name
  2. Project Name
  3. NameSpace Name
  4. File Name
  5. Method Name
  6. Line Number

What I already know is that using

System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(e, true);

I can have access to some of these information(full path of file, line number, etc). But still this information is not all I need. For example, I do not know how to extract solution name or namespace name from trace. Apparently parsing the path for the file is also not an option because different errors can have several layers of file and folders hierarchy and one global rule does not work for all of the errors.

I wonder is there any way to have access programmatically to these info?

Many thanks.

In all likelihood you're not going to get something totally ideal for what you're asking for, but I'll share some tools and thoughts you might not have known about or considered:

  1. There are some attributes ( CallerFilePathAttribute , CallerLineNumberAttribute , and CallerMemberNameAttribute which, when added to an optional method parameter, will cause the compiler to automatically insert a default value based on the context of the code being compiled. You could create a helper method with attributes like this to capture the information you want.
  2. There are tools like Fody, known as "IL Weavers", which can run after the main compile process and change the compiled code in a particular way. For example, your code could be written to make a simple call to one method, but when it's compiled the weaver could change the code to create a bunch of contextual information and pass it to a logging method.
  3. If you're organizing your code well, you can often ensure that the namespace, class, and method (which are all captured as part of the stack trace) are enough information that you can guess the solution, project, and File Name.
  4. When you're catching an exception, you typically want to either log what happened and handle the exception in a particular way, or simply wrap the exception in another exception with more contextual information. If you choose the latter, then the namespace, class, and method name will get included in the stack trace of the thrown exception. So when it's logged further up the stack you'll have access to that data.

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