Exception Handling ActionMessage.Invoke

Topics: Actions & Coroutines, Extensibility
May 24, 2011 at 10:25 AM
Edited May 24, 2011 at 10:26 AM

Hi

We are in the process of creating a prototype version of software. For this,we would like to be able to catch exceptions thrown by caliburn generally, more specifically if we could handle the exception(s) thrown by ActionMessage.Invoke "No target found for method.....".  We would still like to display a recoverable error and have our own MessageBox class for doing so.  Is this possible and how?

Regards

David

May 24, 2011 at 11:22 AM
Edited May 24, 2011 at 11:23 AM

Well, you could inherit from the standard ActionMessage and override Invoke with something like this:

public class CustomActionMessage : ActionMessage
    {
        protected override void Invoke(object eventArgs)
        {
            try
            {
                base.Invoke(eventArgs);
            }
            catch(Exception e)
            {
                // You should replace this with something better :)
                MessageBox.Show(e.Message);
            }
        }
    }

Then you need to tell the parser that it should create your CustomActionMessage

public class AppBootstrapper : Bootstrapper
    {
        
        protected override void Configure()
        {
            Parser.InterpretMessageText = (target, text) =>
                new CustomActionMessage() {MethodName = Regex.Replace(text, "^Action", string.Empty).Trim()};

            // ...
        }
    }
May 24, 2011 at 1:26 PM
Edited May 24, 2011 at 1:27 PM

There is also a configurable delegate in ActionMessage (ActionMessage.InvokeAction) you can tweak without the need of altering the Parser.

Here is a discussion on implementing a general error handling while taking into account coroutine execution, too:
http://caliburnmicro.codeplex.com/discussions/244394 

It involves a [Rescue] attribute, but the tecnique is applicable even without it.

May 24, 2011 at 2:37 PM

Thanks kmees/marcoamendola.

I think I'm going to use combination of both of your answers. kmees, your solution works well when the method is missing from the VM and marcoamendola, your suggestion is ideal when the method on the VM is present but throws an exception.

 

Regards

David