介绍微软发布的Exception Management Application Block

为了更好得管理应用程序中出现异常后如何发布给客户,如是通过电子邮件通知管理员,或是将异常信息写入日志,还是通过友好的信息直接显示在页面. 为此微软封装了一个异常管理模块EMAB.

通常情况下我们这样写异常处理代码:

Try
  ... code that might cause an exception ...
Catch ex as Exception
  ... connect to database ...
  ... insert a row into an ExceptionLog table, adding details
      about the exception ...
End Try

但是这样做对于改变异常报告行为是很麻烦的,如果我们采用EMAB, 就可以这么写:

Try
  ... code that might cause an exception ...
Catch ex as Exception
  ExceptionManager.Publish(ex)
End Try

EMAB里有一个类即ExceptionManager,它的Publish方法接收一个异常实例.
然后对报告异常的处理是由一个继承了IExceptionPublisher接口的类决定的,当然这个接口定义在EMAB里.然后我们还要在著名的WEB.CONFIG文件里注册这个实现了的接口类和其所在的程序集.

举个例子,类DBExceptionPublisher实现了接口IExceptionPublisher:

Imports Microsoft.ApplicationBlocks.ExceptionManagement
Imports System.Web
Imports System.Data.SqlClient
Imports Microsoft.ApplicationBlocks.Data

Public Class DBExceptionPublisher
    Implements IExceptionPublisher

    Public Sub Publish(ByVal exception As System.Exception, _
               ByVal additionalInfo As NameValueCollection, _
               ByVal configSettings As NameValueCollection) _
                   Implements IExceptionPublisher.Publish
        Try           
            SqlHelper.ExecuteNonQuery(GlobalConnectionString,
                    CommandType.StoredProcedure, "sp_AddException", _
                    New SqlParameter("@Message", exception.Message))
        Catch ex As Exception
            HttpContext.Current.Response.Write("FATAL ERROR:<br>" & _
                               ex.StackTrace & "<br><br>" & ex.Message)

            HttpContext.Current.Response.Flush()
            HttpContext.Current.Response.End()
        End Try
    End Sub
End Class

然后在WEB.CONFIG里这么注册:

<configuration>
  ...
  <exceptionManagement mode="on">
    <publisher assembly="MyProjectExceptionBlock"
                  type="MyProjectExceptionBlock.DBExceptionPublisher" />
  </exceptionManagement>
  ...
</configuration>

我们在程序这么写异常处理代码:

Imports Microsoft.ApplicationBlocks.ExceptionManagement

Public Class logon
    Inherits System.Web.UI.Page

    Private Sub Page_Load(ByVal sender as Object, ByVal e as EventArgs)
      Try
         ... do something that might cause an exception ...
      Catch ex as Exception
      ExceptionManager.Publish(ex)
      End Try
    End Sub
   
    ...
End Class

这样,系统里的异常报告行为是直接在页面上显示异常信息,如果要更改为通过邮件通知管理员,那么我们还可以写一个类继承接口IExceptionPublisher,在WEB.CONFIG里更新一下注册即可.

Exception Management Application Block (EMAB)的下载地址如下:

http://download.microsoft.com/download/VisualStudioNET/emabref/RTM/NT5/EN-US/ExceptionManagementApplicationBlock.msi

你可能感兴趣的:(application)