Introduction
Every application needs to show user-friendly messages when something goes wrong, along with exception details and a stack trace for the developers. In this article, I am going to show how to display a user-friendly error message.
Solution
There are many pieces of the puzzle, and it's very easy to plug them together. Following are the pieces of the puzzle:
Message
class: It stores the message details you need to display for the developer.
- Global.asax: Traps the unhandled errors; for every unhandled exception, the
Application_Error
event is triggered.
- Error page: To display error to the user.
- Web.config: Last but the least, the settings to redirect the exception to the error page.
The Message
class is the easiest step; create a class Message
and add LastException
as a static property. I'll come back to static later on when explaining the multithreading issue. In Global.asax, in the Application_Error
event, write this code:
Message.LastException = Server.GetLastError().GetBaseException();
string message = "Error Caught in Application_Error event\n" +
"Error in: " + Request.Url.ToString() +
"\nError Message:" + Message.LastException.Message.ToString() +
"\nStack Trace:" + Message.LastException.StackTrace.ToString();
The first line gets the last exception and saves in the Message
class' LastException
property. The error page is very simple, and has a link to display the message details useful for the developer. The code for this project is attached, so please download the code for testing. Here is piece of code that is included in the hyperlink click event:
if (this.MessagePanel.Visible)
{
this.MessagePanel.Visible = false;
this.DetailLinkButton.Text = "Show Details";
}
else
{
if (Message.LastException != null)
{
this.MessageTextBox.Text = "Error Caught in Application_Error event\n" +
"Error in: " + Request.Url.ToString() +
"\n\nError Message:" + Message.LastException.Message.ToString() +
"\n\nStack Trace:" + Message.LastException.StackTrace.ToString();
}
else
{
this.MessageTextBox.Text = "There is no exception.";
}
this.MessagePanel.Visible = true;
this.DetailLinkButton.Text = "Hide Details";
}
The above code is very simple, and displays the exception details in a textbox. Web.config: Here is the thing everybody knows, redirect to the error page.
<customErrors mode="On" defaultRedirect="showError.aspx">
</customErrors>
Add the above configuration to the web.config in the system.web
section.
That's all, your application is ready to handle exceptions. Oh that multi-user, threading issue. As the Message
class has this static property, there is a chance that the exception details may not be correct. It can be fixed by synchronization, but I guess you don't need it unless you have thousands of simultaneous users.
Conclusion
I have explained just one way of showing the exceptions, and there are millions of other ways to do the same.
Happy coding!