Question - How do I setup a global exception handler for my application

J.D. Meier, Alex Mackman, Blaine Wastell, Prashant Bansode, Andy Wigley, Kishore Gopalan

Applies to

Answer:

To set up a global exception handler for your application, write your exception handling code in the Application_Error event handler that is implemented in Gloabal.asax. This event is raised when exceptions are allowed to propagate from page-level error handlers or if there is no page error handler. Ideally, the exception handling code you write in the Application_Error method will collect and log as much exception details necessary for you to diagnose the error. An unhandled exception might leave your application in an unstable and un-usable form, hence as a fall back mechanism you should always implement a global exception handler. A sample global exception handler that writes exception details to the event log is shown below:

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
  <script language="C#" runat="server">
    void Page_Load(Object Src, EventArgs E)
    {
      if (Page.IsPostBack == false)
      {
         DataSet dataToBind = new DataSet();
         SqlConnection myConnection = new SqlConnection("Server=ServerName; database=Pubs; user id=UID; password=PWD;");
         SqlDataAdapter myCommand = new SqlDataAdapter("select * from Authors", myConnection);
         myCommand.Fill(dataToBind, "Authors");
      
        // Binding the DataView object with DataGrid.
        MyDataGrid.DataSource = new DataView(dataToBind.Tables["Authors"]);
        MyDataGrid.DataBind();
     }
   }
  </script>
  <body>
    <form method="GET" runat="server">
      <h3><font face="Verdana">Caching Data</font></h3>
      <ASP:DataGrid id="MyDataGrid" runat="server"
        Width="700"
        BackColor="#ccccff"
        BorderColor="black"
        ShowFooter="false"
        CellPadding=3
        CellSpacing="0"
        Font-Name="Verdana"
        Font-Size="8pt"
        HeaderStyle-BackColor="#aaaad" />
      <p>
      <asp:button id="button1" runat="server"/>
    </form>
  </body>
</html>

Attributes

  • Author: J.D. Meier, Alex Mackman, Blaine Wastell, Prashant Bansode, Andy Wigley, Kishore Gopalan

  • Category: Exception Management

  • filePath: ..\Libraries\patterns & practices Library\faq\f01dcd8c-e0dc-43b9-9e55-7db2b4f6247a.xml

  • Pri: 2

  • Rule Type: Implementation

  • Source: patterns & practices Library

  • Status: Release

  • Technology: ASP.NET 2.0

  • Title: Question - How do I setup a global exception handler for my application

  • Topic: Security

  • Type: Question and Answer

  • ID: f01dcd8c-e0dc-43b9-9e55-7db2b4f6247a