I am looking for an application-wide method of catching exceptions thrown by databound property getters (and setters, but that's doable without as much difficulty).
None of these events will catch exceptions thrown by getters:
AppDomain.CurrentDomain.UnhandledException
Application.Current.DispatcherUnhandledException
Application.Current.Dispatcher.UnhandledException
Another idea is to use a custom binding class with an UpdateSourceExceptionFilter as described in this thread. Unfortunately this method only catches exceptions in property setters, not getters.
The final option I have seen is to use a PresentationTraceSources trace listener:
PresentationTraceSources.Refresh();
PresentationTraceSources.DataBindingSource.Listeners.Add(new PresentationLoggingTraceListener());
PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.Error;
This method does appear to do basically what I want. Unfortunately, it only gives me a string, not an Exception, meaning I would have to do a bit of parsing work to get at the actual error.
The TraceListener method would probably work in the end, but it seems a little hackish. Are there any other options that I am missing, or am I pretty much stuck with the TraceListener?
I would suggest an Aspect Oriented Programming (AOP) approach to this problem. It would allow you to inject code at compile time that wraps your getter with whatever you wish, in this case a try/catch and logging. The only one that I've worked with is PostSharp Laos, the free version of PostSharp http://www.sharpcrafters.com.
I believe this is a good place to start, http://www.richard-banks.org/2009/02/aspect-oriented-programming.html, in that example he wraps setters with the ability to automatically call NotifyPropertyChanged. There are several other AOP projects out there you could also use but I've not used them. Here is a nice list: http://www.bodden.de/tools/aop-dot-net. I would suggest weave-based approaches.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With