I am doing some enhancements to existing code. And now I want to log one message whenever and wherever exception occurs.
I can add that message in catch/finally 开发者_运维百科block but there are hundreds of catch blocks.
Can anyone suggest better approach to have the message logged whenever exceptions occurs at any part of the code in the assembly?
Second take:
A good approach is AOP with Postsharp.
I've used in many projects.
You can define an attribute that inherits from a base one of PostSharp API which permits you to intercept any method call of the one where you place your custom attribute.
If you put that attribute in any method, you'll be able to try/catch absolutely any method body, and, in the end, control exceptions and logging them.
You can achieve the same goal with Castle Dynamic Proxy, but this is a run-time solution, since you can create proxy classes with interceptors and instantiate your classes with a factory. Obviously, this is consuming more resources.
Postsharp performs IL weaving, meaning that your interceptors will be injected in your actual code in compile-time, so, you don't loose run-time performance.
Summarizing, you can create a "LogAttribute" and place it in any method you want to log or do things if an exception happens.
This is an interesting issue when you have legacy code you have to deal with.
If you REALLY do not want to change your catch blocks, then I might suggest a workaround :
One option you got is writing aLoggedExceptionInterface
or whatever, and implement aLogEvent
in it, and then audit all of your code scanning for handled exception types and redefening them by adding your interface to them.
For example you would replace IOException
by LoggedIOException
where the latter inherits the first, implementing the LoggedExceptionInterface
on top.
Of course, this might turn out to be heavier than changing catch blocks individually;The choice is yours.
For sure, you've last-chance exception handlers.
ASP.NET has it in the HttpApplication, with the Error event (most of the times in the Global ASAX if you're not using an HTTP Module).
WPF and Silverlight have then in the Application.
And Windows Forms can use the AppDomain.UnhandledException event.
Mika Jacobi is right, this is a bad answer. Sorry for that.
精彩评论