Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling fatal exceptions in ViewModel/Model

I have an application written using the M-V-VM approach.

The data access is done in the Model. If a fatal error occurs here (for example, the connection to the data source is lost), and Exception is thrown. This Exception bubbles up to the ViewModel.

However, because the original trigger of the data access was a data binding, WPF swallows this exception (it is only logged in the output window when the app is run under the debugger).

I'd rather this exception remained unhandled so my application-wide unhandled exception handler could pick it up, log it and gracefully exit. How can I achieve this?

like image 824
Ian Gregory Avatar asked Mar 01 '10 02:03

Ian Gregory


People also ask

How to handle exceptions in coroutine?

When a coroutine fails with an exception, it will propagate said exception up to its parent! Then, the parent will 1) cancel the rest of its children, 2) cancel itself and 3) propagate the exception up to its parent.

How do I handle exceptions in coroutine Android?

It is possible to customize the default behavior of printing uncaught exceptions to the console. CoroutineExceptionHandler context element on a root coroutine can be used as a generic catch block for this root coroutine and all its children where custom exception handling may take place. It is similar to Thread.

How do you catch exceptions in Kotlin?

We can use the try-catch block for exception handling in Kotlin. In particular, the code that can throw an exception is put inside the try block. Additionally, the corresponding catch block is used to handle the exception.


2 Answers

You could queue an exception-throwing action on the dispatcher.

    // This property is connected to the window using databinding
    public string ExceptionThrowingBoundedField
    {
        get
        {

            try
            {
                // This function might throw an exception
                return GetValueFromDatabase();               
            }
            catch (Exception ex)
            {
                ApplicationException exWrapper = new ApplicationException(
                    "Wrapped Exception",                                                     
                     ex
                );
                Action throwException = () => { throw exWrapper; };
                Dispatcher.CurrentDispatcher.BeginInvoke(throwException);
                return "";
            }
        }
    }
like image 115
Andrew Shepherd Avatar answered Oct 18 '22 00:10

Andrew Shepherd


Recently come across a way of getting around the swallowed exception problem in a global way.

Create a custom binding class and override UpdateSourceExceptionFilter - see sample in this thread.

Unfortunately this is just WPF 4.0 and not SL 4.0.

like image 6
Adrian Russell Avatar answered Oct 18 '22 01:10

Adrian Russell