How to catch all exceptions at class level in CSharp?
I have a class like:
class SampleRepositoryClass
{
void MethodA()
{
try
{
//do something
}
catch(Exception ex)
{
LogError(ex);
throw ex;
}
}
void MethodB(int a, int b)
{
try
{
//do something
}
catch(Exception ex)
{
LogError(ex);
throw ex;
}
}
List<int> MethodC(int userId)
{
try
{
//do something
}
catch(Exception ex)
{
LogError(ex);
throw ex;
}
}
}
In above example, you can see that in each methods (MethodA, MethodB, MethodC) have try...catch blocks to log the errors and then throw to higher level.
Imagine that when my Repository class might have more than hundred methods and in each method I have try...catch block even if there is only single line of code.
Now, my intention is to reduce these repetitive exception logging code and log all the exceptions at class level instead of method level.
Why re-invent the wheel, when there is such a thing as FREE Post Sharp Express. It's as easy as adding the PostSharp.dll
as a reference to your project. After doing that, your repository would look like the following:
[Serializable]
class ExceptionWrapper : OnExceptionAspect
{
public override void OnException(MethodExecutionArgs args)
{
LogError(args.Exception);
//throw args.Exception;
}
}
[ExceptionWrapper]
class SampleRepositoryClass
{
public void MethodA()
{
//Do Something
}
void MethodB(int a, int b)
{
//Do Something
}
List<int> MethodC(int userId)
{
//Do Something
}
}
Adding the ExceptionWrapper
attribute on the class, ensures all properties and methods are encapsulated within a try/catch block. The code in catch will be the code you put in the overriden function OnException() in ExceptionWrapper.
You dont need to write code to rethrow as well. The exception can also be automatically re-thrown if correct flow-behaviors are provided. Please check the documentation for that.
You're being too defensive. Don't overuse try..catch
only catch it where you need it.
In this case consider catching exceptions thrown by interacting with your class outside of your class. Remember exceptions will be propogated.
使用策略注入应用程序块,Castle,Spring.NET等库。这些库允许您将行为注入异常捕获。
链接地址: http://www.djcxy.com/p/25866.html上一篇: Python:如何忽略异常并继续?