[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Exception Handling in .NET 2.0 c# web application

Posted on 2009-04-22
11
Medium Priority
?
651 Views
Last Modified: 2013-11-17
Hello Gurus,

I have a web app where I need to handle some exceptions. I cannot seem to figure out how to make this work, and keep getting "unhandled exception" and errors that there is no code available for the current location.

My code is below.

All I want to do is catch the error that occurs when I try to rebind a datagrid. I want to log the error in my database (which works fine), then display a friendly error message to the user (this does not work fine).

I have a try catch finally block for my grid rebind() statement.

I have customErrors indicated in my web.config file. A general page and one for status codes 500, 404, and 403.

I want to catch the exception in the code behind, log it with my stored proc, then gracefully display one of my pages with my own error message string that I set in the code behind when I tried to rebind the grid.

I don't want to show a message box. I want to redirect the user to my own custom error page.

Your help is totally appreciated!
web.config:
	  <customErrors defaultRedirect="Error.aspx" mode="RemoteOnly">
		  <error statusCode="500" redirect="Error500.aspx?errmsg="/>
		  <error statusCode="404" redirect="FileNotFound.aspx"/>
		  <error statusCode="403" redirect="AuthorisationFailed.aspx"/>
		  
		 </customErrors>
 
 
aspx.cs code behind the grid page:
try
            {
                LiveGrid.Rebind();
            }
 
            catch (ArgumentOutOfRangeException ex)
            {
                LogError(ex);
                //Console.WriteLine("Error: {0}", "test error message");
                //throw new Exception("Exception Handle:", ex);
            }
            catch (ArgumentException ex)
            {
                LogError(ex);
            }
            //catch (Exception ex)
            //{
            //    string str;
            //    str = "We are sorry for the inconvienience, but there appears to be a problem with your access. Please contact an IT technician.";
            //    str += "\n";
            //    str += "Source: " + ex.Source;
            //    //str += "\n" + "Message: " + ex.Message;
            //    //str += "\n" + "\n";
            //    //str += "\n" + "Stack trace: " + ex.StackTrace;
            //    //lblError.txt = str;
 
            //    //throw ex;
            //    //throw new Exception("Exception Handle:", ex);
 
 
            //    throw;
            //}
            catch (InvalidOperationException ex)
            {
                LogError(ex);
            }
            catch (Exception ex)
            {
                LogError(ex);
            }
            finally
            {
            }
 
Global.asax.cs (do I even need this page???):
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
 
namespace AJAXEnabledWebApplication1
{
    public class Global : System.Web.HttpApplication
    {
 
 
        protected void Application_Error(Object sender, EventArgs e)
        {
            Exception ex = Server.GetLastError();
            Response.Write("Handled error from Application <br>");
 
        }
 
        protected void Global_Error(Object sender, EventArgs e)
        {
            Exception ex = Server.GetLastError();
            Response.Write("Handled error from Global <br>");
        }
    }
}

Open in new window

0
Comment
Question by:rss2
  • 5
  • 5
11 Comments
 
LVL 39

Expert Comment

by:abel
ID: 24206441
An unhandled exception handler should be put inside the global.asax file on the Application_Error event handler. That way you can deal with any error and log them prior to the displaying of the friendly error page to the user. Documentation: http://msdn.microsoft.com/en-us/library/system.web.httpapplication.error.aspx

Note that the uncaught errors are always also logged to the event viewer (in case it is run with IIS). With the event viewer you can still research errors that have happened before you created this error handler.

The Exception object can be accessed by the GetLastError method from with the Application_Error event.
0
 

Author Comment

by:rss2
ID: 24206631
So how exactly would I do this? What do I put in the try catch block of the rebind statement in the code behind of the grid? And what do I put in the global.asax.cs? Where do I write the customised error message?

Thanks
-rss2
0
 
LVL 39

Expert Comment

by:abel
ID: 24206744
Those are loads of questions ;-). The try/catch is ok as it is, but I would remove the catch(Exception), because that will catch ALL exceptions, giving you little options to know what is wrong and how to recover.

In general: try/catch should be used if you have a way to recover from certain exceptions. The rest should be left unhandled and show a nice message to the user (the errorpage you already have).

In other words: if all you would have done in the try/catch is log the error and then show an error page, you should strongly consider removing that try/catch block and leave the unhandled exception handler to do the job.

What you put in the global.asax is whatever you want to do to log your statement. Considering your code above, that could be:

protected void Application_Error(object sender, EventArgs e)
{
    Exception exc = Server.GetLastError();
    LogError(exc);
}

Open in new window

0
Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

 
LVL 9

Expert Comment

by:Gorkem Yuksel
ID: 24208126
Are you sure that your LogError() method is error free?  This may be where you are erroring out on something else.

Cheers,

G.
0
 

Author Comment

by:rss2
ID: 24208390
Cool, abel. Thanks. I thought it was better practice to have try catch blocks, than to rely on the web.config and global.asx files to do the error handling. Would you agree? Can you give me an example of the "best best practice" in this situation? What would wow an Experts Exchange genius, say.. I just want to make sure I'm doing something that's not half-assed (or half-arsed, depending on where you're from..).

Gyuksel, yes good thought, but the LogError() function and stored proc work without errors.

0
 

Author Comment

by:rss2
ID: 24208470
The thing is, even if I leave the try catch as is, and remove the catch (Exception ex), I keep getting the unhandled exception and that there is no source code errors. And in the end none of my error pages show, and the application just hangs. Most frustrating. I just need to know what should go in the try catch so as not to get those messages and so I can display an error page with my own custom error string.
0
 
LVL 39

Accepted Solution

by:
abel earned 2000 total points
ID: 24208653
First an answer to your last comment: there must be something else wrong. That has nothing to do with the error handling we have been discussing. If the catch(Exception) does not catch it, if the Application_Exception does not get it and if the customerrorpage is not shown, something's seriously wrong. Don't try to catch that, try to solve it :)

There are quite a bunch of errors that are uncatchable. Also, some errors cannot be caught by the normal try/catch because they don't inherit from Exception. But in general, you shouldn't worry about those. Again, your error is a sign that something is seriously wrong, so let's solve that first (and show a detailed as possible description here, including what the Event Viewer says, including a screenshot of the error in the browser).

If you have debug="true" the custom error pages will never show.

> Would you agree?

There have been whole books written on error handling and exception handling. Some books treat the subject well, some don't. There's also some disagreement between what good exception handling is. But the general thought is always: only catch what you can catch and what you can do something about, don't catch something that would only have you re-throw the error after logging it. There may be an exception handler higher up the hierarchy that is registered to this exception and you should let it do its job.

Exceptions are what it says: exceptional situations. Some exceptional situation can be anticipated, but more often, you should just let it throw, because your business logic should've already taken care of all the possible cases. And if not, the exception is on its correct place and should propagate itself all the way up.

-- Abel --
0
 

Author Comment

by:rss2
ID: 24212645
Thanks for the answer. I understand the point of exception handling now, but I still don't understand how to execute it properly.

My application is erring the way it does because I forced the error, so that I can test exception handling.

*Sigh* chicken or the egg situation..

The error I'm forcing is a datagrid that is rebinding and the data is NOT there.

It's a fatal error in my situation, but it shouldn't be I should think, if I handled it correctly. And here I am back at square one.

Has anyone else had to handle exceptions when executing a rebind on a datagrid?

Thanks,
rss2
0
 
LVL 39

Expert Comment

by:abel
ID: 24213331
> The error I'm forcing is a datagrid that is rebinding and the data is NOT there.
> Has anyone else had to handle exceptions when executing a rebind on a datagrid?

yes, of course. This is exactly the type of error where I would say: something serious is wrong. Show a page "down for unexpected error, please try again in a few minutes" or something similarly nasty.

Now, back at your error that you want to catch. Can you give the specific exception type and a piece of the first few lines of the stacktrace? Then  can help you further upon solving how to catch this one.

-- Abel --
0
 

Author Comment

by:rss2
ID: 24215867
Thanks for your help, abel. However I did find this post to be exactly what I was looking for..
http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/Q_24197041.html?sfQueryTermInfo=1+10+c+displai+error+except+messag+page

0
 
LVL 39

Expert Comment

by:abel
ID: 24216777
ah, good. Those pages describe handling Page_Error, if I see that correctly (but I only glimpsed over it). I thought you wanted a global error handler... and a try/catch for this one. Sorry if I misunderstood and glad it worked out for you.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Wufoo.com provides powerful tools for surveying targeted groups, and utilizing data from completed surveys to find trends, discover areas of demand or customer expectation, and make business decisions on products or services.
Learn how to set-up PayPal payment integration in your Wufoo form. Allow your users to remit payment through PayPal upon completion of your online form. This is helpful for collecting membership payments, customer payments, donations, and more.
Suggested Courses

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question