Wednesday, April 17, 2019

ASP.NET: create an error page to display unhandled exceptions


Step 1: In Global.aspx, create the Application_Error() method to trap the error:

<script runat="server">
... ...
  void Application_Error(object sender, EventArgs e)
  {
    // Transfer the server error to the error page.
    Server.Transfer("~/ErrorPage.aspx");
  }
 ... ...
</script>

Step 2: Add the error message to ErrorPage.aspx:

<body>
... ...
<p><asp:Label ID="errorMessage" runat="server" /></p>
... ...
</body>

Step 3: In the code-behind of ErrorPage.aspx, i.e. ErrorPage.aspx.cs, add code in Page_Load:

protected void Page_Load(object sender, EventArgs e)
{
  Exception ex = Server.GetLastError();
  if (ex != null && ex.GetType() == typeof(HttpUnhandledException))
    ex = ex.InnerException;

  if (ex != null)
    errorMessage.Text = ex.Message;

  Server.ClearError();
... ...
}

However, for security reasons, this version of ErrorPage.aspx should be used only in a development environment. In production, you don't want to display the exceptions to the end user because that might leak information of your system.

No comments:

 
Get This <