Friday, December 20, 2013

Simple and secure exception handling for .NET web applications

It is best practice not to display details of an exception on the page visible to anyone.  To hide these details, simply add the following to your web.config.
<configuration>
  <system.web>
    <customErrors mode="On" defaultRedirect="WebPages/ErrorPage.aspx"></customErrors>
  </system.web>
</configuration>
You can also change the mode attribute to "RemoteOnly" to only hide errors if viewing the site on a machine other than the web server.  The redirect simply takes the users to a page other than the "yellow screen of death" page that ASP provides.

It is also imperative to add a Global.asax file to your web application project.  You'll want to log anything that fires off the Application_Error event since these represent any unhandled exceptions and the details will no longer be visible on the screen.  Something like this will accomplish that:
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    ' Fires when an error occurs

    Dim MyException As Exception = Server.GetLastError()

    ' Log the exception details here.
End Sub

No comments:

Post a Comment