Click here to Skip to main content
15,885,278 members
Articles / Web Development / ASP.NET
Article

Custom Error messages using Global.asax and Membership model

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
11 Oct 2013CPOL3 min read 7.6K   1  
Scenario: Using ASP.NET membership model to display custom error messages to general users of a website. Send an email to a Webmaster with all the

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

Scenario: Using ASP.NET membership model to display custom error messages to general users of a website. Send an email to a Webmaster with all the details of such an exception. Also in development environment only detailed exceptions are to be displayed and no custom error messages are displayed.

Environment: VS 2005, ASP.NET 2.0

Requirements:

  • The ASP.NET membership and authentication model should be used in the project
  • In order to send an email one should be aware of the smtp address to be used

By following the below steps above stated scenario can be achieved:

Step1: Add a Custom Error page to the project and call it is as may be ErrorMessage.aspx

Step2: Add a Global Application class to an existing project and call it as the default Global.asax

Step3: In Global.asax page under Application_Error sub-routine add the following code:

Vb.Net Code

If (Context IsNot Nothing) And (Context.User.IsInRole("Admin")) Then 'check if user is a Admin
            Dim err As Exception = Server.GetLastError() 'Get the last error from the server
            Response.Clear()
            Response.Write("<h1>" & err.InnerException.Message & "</h1>") 'Write error title and the actual error message
            Response.Write("<pre>" & err.ToString & "</pre>")
            Server.ClearError()
        End If
If (Context IsNot Nothing) And (Context.User.IsInRole("Admin") = False) Then 'If user is not a Admin
            Dim err As Exception = Server.GetLastError()
            Dim msgMail As New MailMessage()
            msgMail.From = New MailAddress("abc@xyz.com") 'Mention from email address
            msgMail.Subject = "Error"
            msgMail.To.Add(New MailAddress("wer@xyz.com")) 'Mention to email address
            msgMail.To.Add(New MailAddress("wty@asd.com"))
            Dim errorurl As String = Request.Path
            Dim ErrorTitle As String = Err.InnerException.Message
            Dim ErrorMessage As String = Err.ToString
            msgMail.IsBodyHtml = True
            Dim strBody As String = "<html><body>" + "An error has occurred. A user requested the page " & errorurl &    "<br/>" & ErrorTitle & "<br/>" & ErrorMessage & ". " + " </body></html>"
            msgMail.Body = strBody
            Dim smtpMail As SmtpClient
            smtpMail = New SmtpClient("xyz.com") 'Mention the smtp address
            smtpMail.Send(msgMail) 'Send the email
            msgMail.Dispose()
            Server.ClearError()
            Server.Transfer("ErrorMesage.aspx") 'Direct the user to the custom error page
        End If

 

C#.Net Code

 <%@ Import Namespace="System.Net.Mail"  %>

     // Code that runs when an unhandled error occurs
        HttpContext context;
        context = HttpContext.Current;
       
        Exception err = Server.GetLastError();
       
        //check if user is a Admin
        if ((Context != null) && (Context.User.IsInRole("Admin")))
        { 
            //Get the last error from the server
            Response.Clear();
            Response.Write("<h1>" + err.InnerException.Message + "</h1>");
            //Write error title and the actual error message
            Response.Write("<pre>" + err.ToString() + "</pre>");
            Server.ClearError();
        }
        if ((Context != null) && (Context.User.IsInRole("Admin") == false))
        {
            MailMessage msgMail = new MailMessage();
            msgMail.From = new MailAddress("abc@xyz.com");
            //Mention from email address
            msgMail.Subject = "Error";
            msgMail.To.Add(new MailAddress("wer@xyz.com"));
            //Mention to email address
            msgMail.To.Add(new MailAddress("wty@asd.com"));
            string errorurl = Request.Path;
            string ErrorTitle = err.InnerException.Message;
            string ErrorMessage = err.ToString();
            msgMail.IsBodyHtml = true;
            string strBody = "<html><body>" + "An error has occurred. A user requested the page " + errorurl + "<br/>" + ErrorTitle + "<br/>" + ErrorMessage + ". " + " </body></html>";
            msgMail.Body = strBody;
            SmtpClient smtpMail = default(SmtpClient);
            smtpMail = new SmtpClient("xyz.com");
            //Mention the smtp address
            smtpMail.Send(msgMail);
            //Send the email
            msgMail.Dispose();
            Server.ClearError();
            //Direct the user to the custom error page
            Server.Transfer("ErrorMesage.aspx");
        }

 

 

After adding the code build and test your project by deliberately creating an error in the project. Make sure that the error induced in the project is a run-time error. Try to test both the cases for an Admin and also for a Non-Admin.

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.

The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.
This is a Collaborative Group

754 members

Comments and Discussions

 
-- There are no messages in this forum --