C# .NET - Exception Handling - Asked By Naresh Kumar on 20-Jan-10 12:33 AM

Hi All,

Can any one tell me how to display the Exception details to the users accessing the website, if they got any error in any page in the website.

Thanks in advance.


re - Santhosh N replied to Naresh Kumar on 20-Jan-10 12:48 AM

It basically boils down to the point how good the exception details you need to show to the users..

If you wanted to show whole exception details you can have a seperate div and assign the value to that div in the page or you could customize the exception and show user friendly messages insetad of exact esceptions..

But, its always better to have a seperate error page f ro the site and show the error meesages in that by redirecting that error page..

You could check here for more info on custom error pages designing in asp.net for exception handling..

http://www.codeproject.com/KB/aspnet/ErrorHandlingASPNET.aspx

and

http://aspnetresources.com/articles/CustomErrorPages.aspx

exception handling global.asax - Kalit Sikka replied to Naresh Kumar on 20-Jan-10 12:57 AM

Here you want exceptions to handle in Global.asax

You can't debug a problem if you don't know that it exists. After you take your web application live, you are no longer the only one who is using it (hopefully), so you need an effective plan to track exceptions when they occur while others are surfing your site. A great way to do this is to implement an exception handler at the application level. This will allow you to consolidate the logging and notification parts of your exception handling in one convenient place. As you'll see from the code examples that follow, your global exception handler can handle both specific exceptions that you trap in your code and generic unhandled exceptions

void Application_Error(object sender, EventArgs e)
{
   //get reference to the source of the exception chain
   Exception ex = Server.GetLastError().GetBaseException();

   //log the details of the exception and page state to the
   //Windows 2000 Event Log
   EventLog.WriteEntry("Test Web",
     "MESSAGE: " + ex.Message + 
     "\nSOURCE: " + ex.Source +
     "\nFORM: " + Request.Form.ToString() + 
     "\nQUERYSTRING: " + Request.QueryString.ToString() +
     "\nTARGETSITE: " + ex.TargetSite +
     "\nSTACKTRACE: " + ex.StackTrace, 
     EventLogEntryType.Error);

   //Insert optional email notification here...
}



Refer: http://www.developer.com/lang/other/article.php/961301/Global-Exception-Handling-with-ASPNET.htm

And http://www.codeproject.com/KB/aspnet/errorhandling.aspx

Re - Huggy Bear replied to Naresh Kumar on 20-Jan-10 01:02 AM

The recommended practice is to handle the exceptions raised in an application. What I mean by handling is, presenting the users with a meaningfull message and logging the exception information into the log files which can be used for exception tracking purpose. Instead of using the try catch blocks every where, You should be handling the exception globally at a single place. In ASP.NET you can use Application_Error event in Global.asax file for it.

My comments are inlined

void Application_Error(object sender, EventArgs e) 
{
//Get the exception occured as shown below
Exception exception = Server.GetLastError();

//Log the exception using EnterpriseLibrary 
//or other logging components

//Redirect the user to a ErrorPage
//Here CustomErrorpage.aspx is the custom error page created
Response.Redirect("CustomErrorpage.aspx");
}

There is also another way

Use the web.config file's cutomErrors section to display user with the custom error page. Remove the redirect code from the global.asax and use it only for logging the exception. Below the sample custom errors section.

<system.web>
<customErrors mode="On" defaultRedirect="CustomErrorpage.aspx">
</customErrors>
</system.web>


Re - Exception Handling. - DL M replied to Naresh Kumar on 20-Jan-10 01:04 AM

try this code sample

  ExceptionLogger logger = new ExceptionLogger();
logger.AddLogger(new WindowLogger());

Here's the implementation

using System.Windows.Forms;

namespace Utilities
{
/// <summary>
/// Logs errors to a window shown on screen
/// </summary>
public class WindowLogger : LoggerImplementation
{
/// <summary>
/// Logs the specified error.
/// </summary>
/// <param name="error">The error to log.</param>
public override void LogError(string error)
{
Form errorForm = new Form();
if (Application.OpenForms.Count > 0)
{
errorForm.Width = Application.OpenForms[0].Width;
errorForm.Height = Application.OpenForms[0].Height;
errorForm.Left = Application.OpenForms[0].Left;
errorForm.Top = Application.OpenForms[0].Top;
errorForm.StartPosition = FormStartPosition.Manual;
errorForm.TopLevel = true;
errorForm.TopMost = true;
}
else
{
errorForm.Width = 600;
errorForm.Height = 1000;
errorForm.StartPosition = FormStartPosition.CenterScreen;
}

errorForm.Text = "An error has occured:";

RichTextBox errorBox = new RichTextBox();
errorForm.Controls.Add(errorBox);
errorBox.Top = 10;
errorBox.Left = 5;
errorBox.Width = errorForm.Width - 20;
errorBox.Height = errorForm.ClientRectangle.Height - 30 - errorBox.Top;
errorBox.Text = error;
errorBox.Font = new System.Drawing.Font("Courier New", 10);
errorBox.ReadOnly = true;
errorBox.WordWrap = false;
errorBox.ScrollBars = RichTextBoxScrollBars.ForcedBoth;
errorBox.Anchor = AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;

Button errorOk = new Button();
errorForm.Controls.Add(errorOk);
errorOk.Top = errorForm.ClientRectangle.Height - 25;
errorOk.Left = errorForm.ClientRectangle.Width - 5 - errorOk.Width;
errorOk.Text = "&OK";
errorOk.DialogResult = DialogResult.Cancel;
errorOk.Anchor = AnchorStyles.Right | AnchorStyles.Bottom;
errorForm.CancelButton = errorOk;
errorForm.AcceptButton = errorOk;

errorForm.ShowDialog();
}
}
}

display error show image
-------------------
http://www.doogal.co.uk/images/ExceptionLogger.png
Exception Handling - Sakshi a replied to Naresh Kumar on 20-Jan-10 01:11 AM

for exceptin handling you can use the above approaches,

for logging you can use Enterprise Library.



Thanks and Regards,
http://www.CodeCollege.NET
http://www.InterviewsGuru.info


Exception Handling - Sagar P replied to Naresh Kumar on 20-Jan-10 01:11 AM

You can use Customer Error pages once any error occurred in your code. In that you don’t have to worry about handling any error at all, you just need to make some changes in we.config which will take care of all things once any error occures.

You just need to desing one page which will show to user once any error occures.

<customErrors mode="On" defaultRedirect="~/frmErrorPage.aspx">

    <error statusCode="403" redirect="NoAccess.htm" />

    <error statusCode="404" redirect="FileNotFound.htm" />

</customErrors>

Once you add this tag in web.config it will take care of all errors.

See this link for same;

http://www.c-sharpcorner.com/UploadFile/akukreja/CustomErrorHandlingASPNET11142005235614PM/CustomErrorHandlingASPNET.aspx

But if you want to show exact exception to user then I think you need to do something different, like you can design one page and use TRY Catch to handle error, and once any error occurs you can handle it in Catch block. In that you can redirect to error page and pass your expection to that page. And you can display the details in that page as it is.

try

{

     //You code      

}

catch (Exception ex)

{

      //Take error in Session value;     

      Session["Error"] = ex.StackTrace + " " + ex.Message;

      Response.Redirect("frmErrorPage.aspx");

//So in that page you can acess Session value and display the error

}