Example of using Error Handling Application Block for WPF Unhandled Exceptions?

Topics: Exception Handling Application Block
Sep 22, 2011 at 12:31 PM
Edited Sep 22, 2011 at 12:55 PM

Do I catch unhandled exceptions via Application.DispatcherUnhandledException or AppDomain.CurrentDomain.UnhandledException ?

How do I use the Error Handling Application Block for this? Can anyone demonstrate some sample code, etc?

How can the end-user easily send the exception details back to developers?

Basically, I'm looking for some guidance on what best practice is after the unhandled error is caught.

Sep 23, 2011 at 5:50 AM

Hi,

You can use the HandleException method to handle the caught exception:

 void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            ExceptionManager manager = EnterpriseLibraryContainer.Current.GetInstance<ExceptionManager>();
            manager.HandleException(e.Exception, "MyPolicy");
        }

Then configure the error application block to either log the exception to a flatfile or database. Best practice is to also include other information such as stack trace,thread id, etc in the log. Good thing is, EntLib already encapsulated this in the process so you don't have to worry about it.

 

Noel Angelo Bolasoc
Avanade Software
Avanade, Inc.
Contact Us

Jan 18, 2012 at 2:56 PM

Hi Noel,

 

I've come across the same scenario and your suggestion helped me.  I'm however struggling to get hold of the exception thrown from HandleException. How can I get hold of it?

Many thanks

Jan 19, 2012 at 5:40 AM

The code would look something like this:

void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
    ExceptionManager manager = EnterpriseLibraryContainer.Current.GetInstance<ExceptionManager>();

    Exception newException;

    bool rethrow = manager.HandleException(e.Exception, "MyPolicy", out newException);

    if (rethrow)
    {
        // Exception policy setting is "ThrowNewException".
        // Code here to perform any clean up tasks required.
        // Then throw the exception returned by the exception handling policy.
        if (newException == null)
        {
            throw;
        }
        else
        {
            throw newException;
        }
    }
    else
    {
        // Exception policy setting is "None" so exception is not thrown.
        // Code here to perform any other processing required.
        // In this example, just ignore the exception and do nothing.
        Console.WriteLine("Detected and ignored Exception");
    }
}

newException is the new Exception returned from the block (in the case of replace or wrap).

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com 

Jan 19, 2012 at 8:54 AM

Thanks Randy. 

I'd done this way. Just wanted to figure out if there was any better way. 

Appreciate your time on this.