Mark Cooper
Mark Cooper

Reputation: 6884

Throw new Exception and Application_UnhandledException

My Scenario:

I'm using a Silverlight MVVM pattern. All my view models inherit from a BaseViewModel class that maintains some basic values and behaviours.

One of these behaviours determines if the user is authorised to use particular functionality and returns a boolean.

If the function is not located, I want to throw a new exception and catch this in the App.xaml Application_UnhandledException method, and raise my own exception event, something like this:

protected bool IsFunctionEnabled(string FunctionName)
        {
            //fetch the function / role 
            if (_FunctionRoles().ContainsValue(FunctionName))
            {
                KeyValuePair<int, string> kvp = _FunctionRoles().GetEntryByStringValue(FunctionName);

                //determine if the user has been assigned to this role
                return (_UserRoles().ContainsKey(kvp.Key));
            }
        //throw an exception when the function name is not located.
        throw new Exception(string.Format(Constants.UNHANDLED_EXCEPTION, "security role assignment: '" + FunctionName + "' not located."));
    }

I then want this automatically picked up in App.XAML:

private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            // throw this message to the main application exception event handler
            ApplicationEvents.OnExceptionOccurred(this, 
                new ExceptionEventArgs(e.ExceptionObject, 
                    null, 
                    ExceptionImportance.Critical));
        }

My Problem

When the exception is thrown, it is not getting bubbled up the stack. When debugging the exception is hit over and over again, no other code is getting run.

What am I doing wrong here?

Thanks, Mark

Upvotes: 0

Views: 1494

Answers (1)

Mark Cooper
Mark Cooper

Reputation: 6884

I think this is occurring because the exception is getting thrown outside of the UI thread, so there is no other code "waiting to run". Triggering an event here means writing a lot more code, but does allow the UI thread to subscribe to this and render a message in the UI properly.

Upvotes: 1

Related Questions