Reputation: 4882
I have a LoB WPF Application and need to find a way to handle & log exceptions globally.
Right know I doing something like this:
public partial class App : Application
{
public App()
{
this.Dispatcher.UnhandledException += OnDispatcherUnhandledException;
}
void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
string errorMessage = string.Format("An unhandled exception occurred: {0}", e.Exception.Message);
MessageBox.Show(errorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
e.Handled = true;
}
}
The problem is that the SimpleIoC "eats" exceptions thrown in the ViewModel. Example:
public class TestViewModel : ViewModelBase
{
public TestViewModel()
{
throw new Exception("this exception will be catched by SimpleIoC, therefore i'm not able to handle it elsewhere");
}
}
I'm using the MVVMLight ViewModelLocator which looks like this:
public class ViewModelLocator
{
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<TestViewModel>();
}
public TestViewModelTestViewModel
{
get
{
return ServiceLocator.Current.GetInstance<TestViewModel>();
}
}
public static void Cleanup()
{
SimpleIoc.Default.Unregister<TestViewModel>();
}
}
According to this article and this article about exception handling, catching (and swallow) exceptions like this is bad design because it may hide bugs in your application. But I might get this wrong.
Finally, here are my questions: How can I log exception which occur during construction of my ViewModel?
Bottom line: MVVMLight is really great and i love it! Thanks to Laurent Bugnion and every one who contributed to this project so far.
Upvotes: 3
Views: 1212
Reputation: 77
I logged the fact that SimpleIoc seems to eat exceptions that occur within constructors as a bug on codeplex.
You can check the item's status here: https://mvvmlight.codeplex.com/workitem/7681
I've done some more testing and have come to the conclusion that this isn't an issue with SimpleIoc, but is actually a symptom of how WPF buries exceptions within bound properties (in this case the bound "TestViewModelTestViewModel" property on the ViewModelLocator class).
Using SimpleIoc to get an instance of TestViewModel outside of a WPF view/control causes an exception to be thrown (as one would expect). This is then caught by whatever handler is in place at the time.
On the other hand, getting an instance of TestViewModel via SimpleIoc within a bound property just results in a failed binding but the exception then doesn't seem to be "escalated" beyond the internals of WPF. The exception is written to the output window when debugging but this isn't much use in a test/production environment.
So, in a nutshell, I don't think SimpleIoc is burying the exceptions (rather, it's a "WPF thing").
Upvotes: 2