Does it cause all the threads,I mean all the users to stop and increase the wait time http request queue and start to affect the availability of the application ?
If so should we make sure there is no exception left over in an asp.net application to ensure scalability of the application.
Some unhandled exceptions can terminate w3wp.exe. Therefore, you should handle exceptions. Application_Error can't handle which are thrown on another thread (background workers, fire and forget taks). You should use http module for these kind of errors. But it also can't catch stackoverflow erros. You should use some decarations for this, if you want handle exceptions on Application level. Here is more detail.
Other than this I think exceptions will not effect the other users. Exception and performance.
Basically, exceptions shouldn't happen often unless you've got
significant correctness issues, and if you've got significant
correctness issues then performance isn't the biggest problem you
face.
I liked this sentence :)
Does it cause all the threads,I mean all the users to stop and
increase the wait time http request queue and start to affect the
availability of the application
It depends on the exception. For example, OutOfMemoryException will affect all users.
On the other hands, FileNotFoundException wouldn't affect other user.
If so should we make sure there is no exception left over in an
asp.net application to ensure scalability of the application.
Well, we all developers try to write bug free code, but sometimes things slip out of our hand. It is why we use logging to catch run-time exceptions - such as Log4Net, NLog.
Related
I have an ASP.Net website that has custom internal threads, for periodically occurring tasks.
If I get an exception on one of these threads, it is not caught in Global.ASAX's Application_Error() function. It is allowed to bubble up to IIS and I find out about it by reviewing the Event Viewer logs. If I catch the exception then Log4Net will direct an email to me and I should find out about the error relatively quickly.
Is there a way I can trap exceptions on these threads? The app needs to be 'always-on', so an exception that drops the application is a show-stopper.
In a comment you mentioned:
This is a web-site rather than web app.
"Web site" vs. "web app" seems like a moot distinction at this point. There's enough complexity in the code that it's an "application" by pretty much any definition of the word. To that point, if the application host doesn't meaningfully manage thread faults for you (and I wouldn't expect a web application host to do so) then you have to manage them manually.
In this case I see that as one of two options:
Option 1: Don't let your threads end in a faulted state. Whatever your top-level worker item for any given thread is (a method invoked at the start of the thread, a loop repeating operations, etc.), that needs to be essentially fault-proof. No exception should get past that. Which means it needs to be dead simple (so as to not throw exceptions of its own) and needs to catch any and all exceptions from the operation(s) it invokes.
Once caught, do with them as you please. Roll back a unit of work, notify someone of the error, etc.
Option 2: Move the long-running thread operations out of the web application, since web applications aren't really suited for ongoing background processes. A Windows Service or scheduled Console Application is a much more suited application host for that logic.
Yes, bit of a re-write there though.
Is it? It shouldn't be. That's really a matter of how the code was originally architected, not related to the application hosts themselves. Invoking a business operation from one application host is the same as invoking it from another. If the logic is tightly coupled to the application technology, that's a separate problem. And there's no quick fix to that problem. The good news is that once you fix that problem, other problems (like the one which prompted this question) are quick fixes.
My Azure .Net web app uses a shared cache role which can sometimes throw an exception meaning, "retry later" if it is hot swapping. Currently, that causes my web app to error. However, this is thrown before my app has even started up since it is the framework/IIS which has attempted to setup the cache and failed.
How can I catch these exceptions and do something useful when redirecting to an error page would still require my app and config/cache to load, which would cause the exceptions again? Even if I could catch the exception in Application_Error, I don't think I can retry the connection to the cache because I didn't create it in the first place.
Few questions :
Didn't clearly get your question. So it's your client calling cache, who is getting these errors right?
Are you using session state provider for cache? If not, When you said you are not making connections to the cache, what did you mean?
What is the exact error?
Is it intermittent? Is it always happening during role startup, the case u mentioned here?
In my 3.5 .net web application I have a background thread that does a lot of work (the application is similar to mint.com in that it does a lot of account aggregation on background threads). I do extensive exception handling within the thread performing the aggregation but there's always the chance an unhandled exception will be thrown and my entire application will die. I've read some articles about this topic but they all seem fairly outdated and none of them implement a standard approach. Is there a standard approach to this nowadays? Is there any nicer way to handle this in ASP.NET 4.0?
Arguably, the entire application should die if you have an unhandled exception. An unhandled exception means that your program is in an unknown/indeterminate state, and any further processing or user interaction could cause corruption of the program's state, or worse, data corruption.
You're doing the right thing handling exceptions within your thread work. As far as I know, there is no way for a .NET application to "gracefully" deal with unhandled exceptions on background threads - they will always terminate the process.
Certain .NET Framework classes, such as the BackgroundWorker component and the Task Parallel Library in .NET 4 make multithreading easier and handle a lot of the dirty work of exception handling for you, so if it's possible for you to use those instead of implementing your own multi-threaded code, then you should definitely do so. But if those aren't able to help you in a given circumstance, if you must use the ThreadPool or a pure Thread, then be sure not to let any unhandled exceptions escape.
You can always put a try/catch block around your worker thread at a very high level... like right when the thread starts. I'm assuming this is what you're doing already, or something like it. But just keep in mind that you definitely don't want to turn an unknown error into a silent unknown error, because then it's going to be much harder to track down when something goes wrong. Be sure you are logging the exception to the EventLog or your custom app log if you want to just catch it and forget it.
Like Aaronaught says, the application should die when something unexpected happens. But I don't see a problem with just letting your background thread exit/die instead of bringing down the whole application process (in fact, I don't think Aaron is correct here, it won't kill the entire process) I think your question can basically be translated as "is there something magical in ASP.NET that will suddenly solve issues I don't even know about yet?" and the answer to that of course, is no. But you already knew that. :)
I have an ASP.NET C# 3.5 web application that consumes another ASP.NET web service as a web reference. The web service is built into some proprietary hardware device. The problem is that that device has been having troubles and not alwasy accessible. My web application is suffering brcause of it, as it takes over a minute to load. It does load, but not acceptable.
The service is instantiated in a try catch block and no exception is being throw, but the output windows displays:
A first chance exception of type 'System.Net.WebException' occurred in System.dll
I know there is a better way to handle this, but I am drawing blanks.
Any help is appreciated.
UPDATE: Still looking for an answer on how to handle webservices that become unavailable without affecting website.
After tearing it apart, I found the exception. It is a standard "Unable to connect" exception. The problem is now the timeout, I have tried setting the asyncTimeout to 5000 in the web.config under the System.Web -> Pages properties. It is still taking aroung 20 seconds to throw the exception. Any ideas?
If you saw a "first chance exception" but your exception handler didn't get it, that means that the exception was handled elsewhere (swallowed, consumed by an exception handler, etc.) Perhaps something in the .NET libraries already handled that exception, and you need not concern yourself with it in your code. Or maybe you left some exception swallowing somewhere in your code.
You ought to consider using a timeout in your web request.
Simple solution, poll the service using JavaScript after page load.
Without any details regarding frequency/usage of the service and not seeing any code, heres a thought or two.
Its most likely the web method on this hardware that giving the error, so I'd pursue any support options you have (if any), but just for giggles, try this first to see if it helps....
I noticed that some people online said that they were able to get around this (in their scenario) by setting the KeepAlive to false on the requesting object, so that way your aren't inadvertently using an old (stale) connection to the service. You may be trying to "Keep Alive" but the webserver timed out the connection on you. Worth a quick try...
Good Luck!
In addition to the above, I would use a http debugger (like fiddler2) to get a better idea of what is happening on the wire.
I admit it: I don't bother with too much exception handling. I know I should do more but I can never wrap my head around where to start and where to stop. I'm not being lazy. Far from it. It's that I'm overwrought with exception handling ambivalence. It just seems that there is a seemingly infinite number of places in even the smallest app where exception handling can be applied and it can begin to feel like overkill.
I've gotten by with careful testing, validating, and silent prayer but this is a bad programming accident waiting to happen.
So, what are your exception handling best practices? In particular, where are the most obvious/critical places where exception handling should be applied and where are places where it should be considered?
Sorry for the vague the question but I really want to close the book on this once and for all.
Microsoft's Patterns & Practices team did a good job incorporating best practices of exception management into Enterprise Library Exception Handling Application Block
Event if wouldn't use Enterprise Library, I highly recommend you to read their documentation. P&P team describes common scenarios and best practices for exceptions handling.
To get you started I recommend read following articles:
Exception Handling on MSDN
Exception Management in .NET on MSDN
Exception Handling Best Practices in .NET on CodeProject
ASP.NET specific articles:
User Friendly ASP.NET Exception Handling
Global Exception Handling with
ASP.NET
Exception handling in C# and ASP
.Net
The golden rule with exception handling is:
"Only catch what you know how to handle"
I've seen too many try-catch blocks where the catch does nothing but rethrow the exception. This adds no value. Just because you call a method that has the potential to throw an exception doesn't mean you have to deal with the possible exception in the calling code. It is often perfectly acceptable to let exceptions propagate up the call stack to some other code that does know what to do.
In some cases, it is valid to let exceptions propagate all the way up to the user interface layer then catch and display the message to the user. It might be that no code is best-placed to know how to handle the situation and the user must decide the course of action.
I recommend you start by adding a good error page that catches all exceptions and prints a slightly less unfriendly message to the user. Be sure to log all details available of the exception and revise that. Let the user know that you have done this, and give him a link back to a page that will (probably) work.
Now, use that log to detect where special exception handling should be put in place. Remember that there is no use in catching an exception unless you plan to do something with it. If you have the above page in place, there is no use in catching database exceptions individually on all db operations, unless you have some specific way to recover at that specific point.
Remember: The only thing worse than not catching exceptions, is catching them and not doing nothing. This will only hide the real problems.
Might be more about exception handling in general than ASP.NET speific but:
Try to catch exceptions as close to
the cause as possible so that you
can record (log) as much information
about the exception as possible.
Include some form of catch all, last
resort exception handler at the
entry points to your program. In
ASP.NET this could be the
Application level error handler.
If you don't know how to "correctly" handle an exception let it bubble up to the catch all handler where you can treat it as an "unexpected" exception.
Use the Try***** methods in .NET
for things like accessing a
Dictionary. This helps avoid major
performance problems (exception
handling is relatively slow) if you
throw multiple exceptions in say a
loop.
Don't use exception handling to
control normal logic of your
program, e.g. exiting from a loop via
a throw statement.
Start off with a global exception handler such as http://code.google.com/p/elmah/.
Then the question comes down to what kind of application are you writting and what kind of user experience do you need to provide. The more rich the user experience the better exception handling you'll want to provide.
As an example consider a photo hosting site which has disk quotas, filesize limits, image dimension limits, etc. For each error you could simply return "An error has occured. Please try again". Or you could get into detailed error handling:
"Your file is to large. Maximum
filesizes is 5mb."
"Your image is is
to large. Maximum dimensions are
1200x1200."
"Your album is full.
Maximum storage capacity is 1gb".
"There was an error with your
upload. Our hampsters are unhappy.
Please come back later."
etc. etc.
There is no one size fits all for exception handling.
Well at the very basic level you should be handling the HttpApplication.Error event in the Global.asax file. This should log any exception that occurs to a single place so you can review the stack trace of the exception.
Apart from this basic level you should ideally be handling exceptions where you know you can recover from them - for example if you expect a file might be locked then handling the IOException and reporting the error back to the user would be a good idea.