Making Your Error Pages Pretty!
In my opinion your client/user should never see the yellow screen of death. There are numerous ways to redirect the user to a custom error page. In this post I will discuss how to use Application_Error event in the Global.asax file. Let's check out the code that will throw the error.
private string GetObjectFromSession()
{
if (Session["UserName"] == null)
throw new ArgumentNullException("UserName is null","UserName is null. Your session has expired. <res> Please log on to the system to start a new session </res>");
return Session["UserName"] as String;
}
So, the above code will throw the error since I am not storing anything in the Session Object.
You will notice that I am using the <res> ("res") tags inside for the exception message. The "res" means resolution of the problem. I think it is important to give users some information on how to solve the problem and get back on the right track.
protected void Application_Error(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
Exception ex = context.Server.GetLastError();
Response.Write("<link href=\"Stylesheet1.css\" rel=\"stylesheet\" type=\"text/css\" />");
Response.Write(TableHelper.GenerateErrorTable(ex));
context.Server.ClearError();
}
The Application_Error event uses the TableHelper and style sheets to make the error look better or prettier. Take a look at the result shown in the screen shot shown below:

UPDATE:
private static string ReplaceTags(string message)
{
return ((message.Replace("<res>","<span class=\"resolution\">")).Replace("</res>","</span>"));
}
public static string GenerateErrorTable(Exception ex)
{
Table table = new Table();
table.CssClass = "pollTable";
TableHeaderRow headerRow = new TableHeaderRow();
headerRow.CssClass = "pollTitle";
TableHeaderCell headerCell = new TableHeaderCell();
headerCell.Text = "ERROR DETAILS";
headerRow.Cells.Add(headerCell);
Literal litText = new Literal();
litText.Text = ReplaceTags(ex.Message) + " " + ReplaceTags(ex.InnerException.Message);
TableRow row = new TableRow();
TableCell cell = new TableCell();
cell.Controls.Add(litText);
row.Cells.Add(cell);
TableRow resRow = new TableRow();
TableCell resCell = new TableCell();
resCell.Text = ErrorResource.SessionNullError;
resRow.Cells.Add(resCell);
table.Rows.Add(headerRow);
table.Rows.Add(row);
table.Rows.Add(new TableRow());
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
table.RenderControl(htw);
return sw.ToString();
}