简体   繁体   中英

Identify exception origin from exception properties in WPF (C# .Net) app

I am recently assigned a task to extend an existing WPF (C#.Net) application for an error handler. The handler is supposed to display a friendly message with possible easy solution for the user. It is required that I change nearly no code = I can only work in App.xaml.cs code behind. My approach is to try to identify the error from the stack trace and from the properties of the innermost exception. So far, I am using these three identifiers:

string identifierMethod= new System.Diagnostics.StackTrace(ex.GetBaseException()).GetFrame(0).GetMethod().Name;  
string identifierObject = ex.GetBaseException().TargetSite.ReflectedType.FullName;
string identifierHResult = ex.GetBaseException().HResult.ToString();
//ex is the uppermost exception coming to App 

I need to identify the root method and object where the exception originated. Combining these three seems to work for me but I don't think it is very clean and robust and I fear there could be some exception that will have duplicate combination of these three identifiers. Sometimes the innermost exception's stack trace is null, sometimes it seems to me the identifiers do not really describe the lowermost method or object constructor which caused the Exception. I know I could ideally use Exception Data or Source properties assigning some identifiers in try catch block where the Exception originate but I simply cannot. I know similar question were asked but they only gave me what I have now.

Thanks a lot for any suggestions and ideas.

You can use Checked Exceptions to announce the caller methods about the callees' exceptions. And in caller methods, you can easily handle the exception by their types, identify the exception origin, and have a friendly message. To add the Checked Exception feature into the C# , you can use this nugget package: Portia.Roslyn.CheckedException .

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