asp.net Background Threads Exception Handling - asp.net

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. :)

Related

What happens with an exception in Asp.Net with concurrent users

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.

ASP.Net C# 4.0 - How to catch application thread exceptions

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.

Exception handling in a three-tier Asp.Net application

1) To my understanding, in a three-tier Asp.Net application we should implement exception handling in the following way:
a - we should put try-catch block around block of code ( located in any of the three layers ) from which we expect the page to gracefully recover from ( when this code generates an exception )?
b - we shouldn’t put try-catch blocks around code ( located in either of the three layers ) from which we don’t expect the page to gracefully recover from. Instead, Asp.Net application should always manage these unhandled exceptions through global exception handler ( Application_Error/Page_Error )?
2) Is the main benefit of managing unhandled exceptions through Application_Error/Page_Error the fact that this way we centralize error handling in one location?
After all, we could achieve the same results even if these unhandled exceptions (thrown in any of the three layers ) were instead handled ( logged, user redirected to custom error page ... ) at the spot where they were thrown?!
thank you
Not necessarily.
1a - it's quite acceptable for the data layer to have no exception handling. In which case any exception would be handled further up the stack.
1b - the data layer and business layer may not be called via a website, so a particular web page isn't necessarily relevant. For example, a webservice or WPF application may also use these layers.
2 - yes the main benefit is a single location for website error handling.
The main thing you want to avoid is silently swallowing exceptions that cannot be recovered from. (In short, having a try...catch block where you display some error to the user, but don't rethrow the exception, where thereby only the end user is aware that something went awry.)
If an exception happens and you can recover from it, great!
If an exception happens and you can't recover from it, then it is important that the exception details be logged and that the developers are notified of the exception. Typically this is done by letting the exception propagate to the ASP.NET runtime layer so that ASP.NET's Error event will fire. It's a best practice to subscribe to this Error event in some manner so as to log the error details and notify developers. One such tool for logging and notifying in the face of an error is ELMAH, another is the ASP.NET Health Monitoring library.
Also, if I may, I'd suggest this article of mine, which covers the points I made in here more depth and detail: Exception Handling Advice for ASP.NET Web Applications.
Happy Programming!
1a) is correct.
1b) is sort of correct; you may let the exception go up the stack from your model/business layers to the presentation, and display an error message. It doesn't have to go all the way to the Application_Error; Page_Error may be good, but some exceptions might be (relatively) common enough that, while you can not gracefully recover, you should have specific error messages related to them in some contexts.
2) basically; and also as a 'catch all' for exceptions you have not been able to predict and catch in more specific places.

Webservice unavailable

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.

Exception Handling in .net web apps

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.

Resources