Notifying the User

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

The latest Enterprise Library information can be found at the Enterprise Library site.

When you use the Exception Handling Application Block, a frequently required task is to notify the user when an exception occurs. (Generally, this should be completed after the message has been changed to one that is workable for the particular user. For more information, see Displaying User-Friendly Messages.) Depending on the application type, you can do this using a Windows Forms dialog box or a Web page. When an exception cannot be handled within the application, the user must know that something went wrong, along with some guidance of what he or she should do next.

Typical Goals

You want to notify the user that an exception has occurred.

Solution

Create a custom exception handler that constructs and displays a message for the user. Establish the handler as the global exception handler for the application. Include the handler in your exception handling chain.

QuickStart

For an extended example of how to use the Exception Handling Application Block to notify the user, see the QuickStart Walkthrough, Walkthrough: Notifying the User.

Notifying the User

The following procedure describes how to use the Exception Handling Block to notify the user of an exception.

To notify the user

  1. Create a class that derives from TextExceptionFormatter that will format the message for display to the user. The following code demonstrates how to create a customer formatter that does not include the stack trace information in the message.

    public class AppTextExceptionFormatter : TextExceptionFormatter
    {
      public AppTextExceptionFormatter(TextWriter writer, Exception exception): base (writer, exception) 
      {
      }
    
      protected override void WriteStackTrace(string stackTrace) 
      {
      }
    
      protected override void WriteExceptionType(Type exceptionType) 
      {
        base.Indent();
        base.Writer.WriteLine("Type : {0}", exceptionType.FullName);
      }
    }
    
    'Usage
    Public Class AppTextExceptionFormatter
        Inherits TextExceptionFormatter
    
      Public Sub New(ByVal writer As TextWriter, ByVal exception As Exception)
        MyBase.New(writer, exception)
      End Sub
    
      Protected Overrides Sub WriteStackTrace(ByVal stackTrace As String) 
      End Sub
    
      Protected Overrides Sub WriteExceptionType(ByVal exceptionType As Type)
        MyBase.Indent()
        MyBase.Writer.WriteLine("Type : {0}", exceptionType.FullName)
      End Sub
    End Class
    
  2. Create a custom exception handler that displays a dialog to notify the user of an exception. The following code demonstrates how to do this.

    [ConfigurationElementType(typeof(CustomHandlerData))]
    public class AppMessageExceptionHandler : IExceptionHandler
    {
      public AppMessageExceptionHandler(NameValueCollection ignore)
      {
      }
    
      public Exception HandleException(Exception exception, Guid handlingInstanceId)
      {
        DialogResult result = this.ShowThreadExceptionDialog(exception);
    
        return exception;
      }
    
     // Creates the error message and displays it.
     private DialogResult ShowThreadExceptionDialog(Exception ex) 
    {
      string errorMsg = "The following exception was caught by the Quick Start Global Exception Handler:" + Environment.NewLine + Environment.NewLine;
    
      StringBuilder sb = new StringBuilder();
      StringWriter writer = new StringWriter(sb);
    
      AppTextExceptionFormatter formatter = new AppTextExceptionFormatter(writer, ex);
    
      // Format the exception.
      formatter.Format();
    
      errorMsg +=  sb.ToString();
    
      return MessageBox.Show(errorMsg, "Application Error",    MessageBoxButtons.OK, MessageBoxIcon.Stop);
    }
    
    }
    
    <ConfigurationElementType(GetType(CustomHandlerData))> _
    Public Class AppMessageExceptionHandler
      Implements IExceptionHandler
    
      Public Sub New(ByVal ignore As NameValueCollection)
    
      End Sub
    
    
      Public Function HandleException(ByVal e As Exception, ByVal handlingInstanceID As Guid) As Exception Implements IExceptionHandler.HandleException
    
        Dim result As DialogResult = Me.ShowThreadExceptionDialog(e)
    
        Return e
      End Function
    
      ' Creates the error message and displays it.
      Private Function ShowThreadExceptionDialog(ByVal e As Exception) As DialogResult
    
        Dim errorMsg As String = "The following exception was caught by the Quick Start Global Exception Handler:" + Environment.NewLine + Environment.NewLine
    
        Dim sb As StringBuilder = New StringBuilder
        Dim writer As StringWriter = New StringWriter(sb)
    
        Dim formatter As AppTextExceptionFormatter = New AppTextExceptionFormatter(writer, e)
    
        ' Format the exception.
        formatter.Format()
    
        errorMsg += sb.ToString()
    
        Return MessageBox.Show(errorMsg, "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Stop)
      End Function
    
    End Class
    
  3. Create an exception handling policy with the relevant exception types for your application.

  4. Configure the exception type. Specify the PostHandlingAction as None. The None action indicates that the application block will take no further action after the exception handler chain runs.

  5. Add a new custom handler for the specified exception types, setting the handler type to the new handler created in step 1.

  6. Modify your application code to execute the new policy when an exception occurs. The following code demonstrates how to do this.

    try
    {
      // Run code.
    }
    catch(Exception ex)
    {
      bool rethrow = ExceptionPolicy.HandleException(ex, "Global Policy");
      if (rethrow)
        throw;
    }
    
    'Usage
    Try
      ' Run code.
    Catch ex As Exception
      Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Global Policy")
      If (rethrow) Then
        Throw
      End If
    End Try
    

Usage Notes

You should never use a handler that displays a Windows Form or raises message boxes in server applications such as ASP.NET applications and Enterprise Services applications. Doing so can cause the applications to stop responding.

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

The latest Enterprise Library information can be found at the Enterprise Library site.