Sdílet prostřednictvím


Notifying the User

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 suitable 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 receive a notification that an error occurred, 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.

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, Guid handlingInstanceId)
        : base (writer, exception, handlingInstanceId) 
      {
      }
    
      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, ByVal handlingInstanceId As Guid)
        MyBase.New(writer, exception, handlingInstanceId)
      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, handlingInstanceId);
    
        return exception;
      }
    
      // Creates the error message and displays it.
      private DialogResult ShowThreadExceptionDialog(Exception ex, Guid handlingInstanceId) 
      {
        string errorMsg = "The following exception was caught by the Global Exception Handler:" 
                        + Environment.NewLine + Environment.NewLine;
    
        StringBuilder sb = new StringBuilder();
        StringWriter writer = new StringWriter(sb);
    
        AppTextExceptionFormatter formatter = new AppTextExceptionFormatter(writer, ex, handlingInstanceId);
    
        // Format the exception.
        formatter.Format();
    
        errorMsg +=  sb.ToString();
    
        return MessageBox.Show(errorMsg, "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
      }
    }
    
    'Usage
    <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, handlingInstanceId)
    
        Return e
      End Function
    
      ' Creates the error message and displays it.
      Private Function ShowThreadExceptionDialog( _
                ByVal e As Exception, _
                handlingInstanceId As Guid) As DialogResult
    
        Dim errorMsg As String = "The following exception was caught by the 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, handlingInstanceId)
    
        ' Format the exception.
        formatter.Format()
    
        errorMsg &= sb.ToString()
    
        Return MessageBox.Show(errorMsg, "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Stop)
      End Function
    
    End Class
    

    Note

    For detailed information about how to integrate custom providers with the Enterprise Library configuration system and configuration tools see Creating Custom Providers for Enterprise Library.

  3. Create an exception handling policy with the relevant exception types for your application.

  4. Configure the exception type. Specify the post-handling action as None. The None action indicates that the block will not take any 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 2.

  6. Modify your application code to execute the new policy when an exception occurs. The following code demonstrates how to do this. It assumes you have resolved an instance of the ExceptionManager class through the Enterprise Library container and saved it in a variable named exManager. For more information on instantiating objects, see Creating and Referencing Enterprise Library Objects.

    exManager.Process(YourTargetMethod, "Notify Policy");
    
    'Usage
    exManager.Process(AddressOf YourTargetMethod, "Notify Policy")
    

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.