Managing Exception/Error is a common task in any application. In ASP.NET, there are many ways to handle those errors or exceptions, for example, when an error or exception occurrs in an ASP.NET application, the system is going to send a formatted error message to specified developers or teams mentioned in the email list. The difference will be the body of the email will contain exactly the same formatted error as the ASP.NET generated one to display the error or exception details when occurred. For example,
But when an ASP.NET application goes into life, the user should not have to see the above error page where they should see a custom error page which is easy to understand. More information is available here[^].
So in here, the test application will display the default error page when an error occurs in the system as well as send an email with the formatted exception details like in the above image.
To do that, we need to add the following code in the
void Application_Error(object sender, EventArgs e) method to the Global.asax.cs file:
void Application_Error(object sender, EventArgs e)
HttpUnhandledException httpUnhandledException =
new HttpUnhandledException(Server.GetLastError().Message, Server.GetLastError());
GetHtmlErrorMessage() method of the
HttpUnhandledException class will do all the formatting stuff. The
HttpUnhandledException is .NET framework class and to find out more about it, please visit here[^].
The code block to send the email is shown below:
private static void SendEmailWithErrors(string result)
MailMessage Message = new MailMessage();
Message.To = "To address";
Message.From = "FROM addressd";
Message.Subject = "Exception raised";
Message.BodyFormat = MailFormat.Html;
Message.Body = result;
SmtpMail.SmtpServer = "SMTP Sever Address";
catch (System.Web.HttpException ehttp)
To test this, there is a button on the page which triggers an exception; the code for the button is as below:
protected void btnError_Click(object sender, EventArgs e)
throw new Exception("This Exception is raised to test");
The system will display the default error page when an exception occurs and send an email with the formatted exception details as below:
Default error page:
And an email with the formatted exception details:
Please have a look here to get similar Source code[^].