Basic error handling for ASP.NET web sites

To avoid displaying the complicated error messages displayed by the .NET framework, you can direct users to a more user-friendly page by inserting the following tags into your web.config file:

<customErrors mode="RemoteOnly" defaultRedirect="errors/error.aspx">
     <error statusCode="404" redirect="errors/error404.aspx"/>
</customErrors>

Using this method of error handling also has the added benefit of not displaying sensitive server information to the user (or potential hacker). "RemoteOnly" means that the error messages are still displayed in their normal format if viewing the pages on the web server itself. You can also view the error messages in the server's event viewer or e-mail the errors to a system administrator by inserting the following code (or similar) into your global.asax file:

    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        Dim varCurrentException As Exception
        varCurrentException = Server.GetLastError.InnerException()
    
        'E-mail to system administrator
        Dim client As New SmtpClient
        Dim message As New MailMessage
        message.Body = "Error: " & varCurrentException.ToString & "<br/><br/>Source: " & Request.Url.ToString
        message.Subject = "DSC488588 Web Site Error"
        message.From = New MailAddress("name@domain.com", "System Adminstrator")
        message.IsBodyHtml = True 'Assume HTML format for website owner

        message.To.Add("name@domain.com")
        client.Send(message)
    End Sub

Remember that it is better to explicitly handle individual errors (for example, using Try, Catch) rather than relying on this catch-all method for handling all errors. Use this method for detecting any remaining errors but consider handling them individually if they reoccur.

Published Tuesday, April 15, 2008 1:43 PM by gcastner
Filed under: ,

Comments

No Comments