Exception Handling in an ASP.NET HttpHandler
What is considered best practice associated with Exception Handling inside an ASP.NET HttpHandler? Should Exceptions not able to be handled be allowed to flow upwards through the chain as one would do in general or s开发者_运维问答hould all Exceptions be caught and "handled" in the handler and allow nothing past?
My suggestion will be simple: if you cannot "fix the problem" then don't swallow the exception - let it propagate. Otherwise you'll most likely face with unexpected behavior of your application.
All exceptions should be handled, somehow. You need to provide some sort of notification to the user that something went wrong, if an unexpected exception bubbles up past all your exception handlers. There should be some way to notify an admin or programmer (a log, email, or whatever) so that additional code can be added to handle the exception situation. You should try to handle any exceptions that will likely pop up, such as database connectivity issues in case the database goes down. Basically, you want to fail as gracefully as possible within the realm of what you can predict, and if unexpected occurrences occur, trouble shoot what happened, and add additional code to deal with those situations.
Are you talking about HTTP Handlers or HTTP Modules? Because HTTP Handlers are just routine handlers (ASP.NET Pages are just simple HTTP Handlers)
Well, if you meant HTTP Handler, then as I said, it's just like a normal ASP.NET Page. What do you do in your page?
But there are some general guidelines that you have to consider always for exception handling:
- Never let the end user see the exception page (yellow screen of death). This means that you have to always
try/catch
orif
your code to prevent exceptions from being rendered on the screen. - Never swallow a exception. The least work you have to do in any catch block, is to log it.
- Have a centralized exception handling and message translate mechanism, so that your future maintenance is easier.
- Prefer validation and if checks over catching an exception, because catch blocks are expensive.
Why did everybody voted this post down. I just wanted to complete this post guys :)
How you handle an exception depends on the particular scenario, but it should be handled somewhere to find out what went wrong.
You should log as much information as you possibly require (error codes, messages, stacktrace etc) to make it easier to recreate and rectify. You may also want to log lost information (such as any form details) or any security related information.
After the above is done you can just gracefully redirect to a relevant error page.
精彩评论